使用Render Props时React组件未更新,如何实现计数器正常递增?
解决Render Props下Store更新时组件状态不更新的问题
问题核心在于你的数据获取组件没有监听Store的变化,仅在初始化时读取了一次Store值,导致Store更新后组件无法同步最新状态。按以下方式修改即可解决:
1. 给数据组件添加Store订阅逻辑
在负责提供Store数据的组件中,挂载时订阅Store变化,Store更新时同步组件内部状态,卸载时取消订阅避免内存泄漏:
class StoreProvider extends React.Component { constructor(props) { super(props); // 初始化时获取Store当前值 this.state = { count: store.getState().count }; this.handleStoreUpdate = this.handleStoreUpdate.bind(this); } componentDidMount() { // 订阅Store变化,更新时触发组件状态更新 this.unsubscribe = store.subscribe(this.handleStoreUpdate); } componentWillUnmount() { // 组件卸载时取消订阅 this.unsubscribe(); } handleStoreUpdate() { // 将Store最新值同步到组件状态 this.setState({ count: store.getState().count }); } render() { // 通过render props把最新的count传递给子组件 return this.props.render(this.state.count); } }
2. 确保Render Props接收并使用最新值
使用该组件时,直接通过render函数接收最新的count并渲染:
<StoreProvider render={(count) => ( <div> <p>计数器: {count}</p> <button onClick={() => store.dispatch({ type: 'INCREMENT' })}>递增</button> </div> )} />
修改完成后,每次Store中的count更新,组件都会同步状态并重新执行render函数,计数器就能正常递增了。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

