使用redux时,如何在反应组件中处理取消订阅? [英] How should unsubscribe be handled in a react component when using redux?
问题描述
在我的组件中,我有以下内容:
In my component I have the following:
componentWillMount: function () {
this.unsubscribe = store.subscribe(function () {
this.setState({message: store.getState().authentication.message});
}.bind(this));
},
componentWillUnmount: function () {
this.unsubscribe();
},
不调用unsubscribe会导致以下错误:
Not calling unsubscribe causes the following error:
警告:setState(...):只能更新已挂载或挂载的
组件。这通常意味着您在未安装的
组件上调用了setState()。这是一个无操作。
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
我想知道的是我应该分配取消订阅
到这个
还是有更好的地方分配它?
What I'd like to know is should I be assigning unsubscribe
to this
or is there a better place to assign it?
推荐答案
正如 Salehen Rahman 在评论中提到的那样,我最终使用 react-redux 。
As mentioned by Salehen Rahman above in the comments I did end up using react-redux.
根据他们的文档,我创建了两个函数,一个用于将全局状态映射到组件中的props:
Following their documentation I created two functions, one to map the 'global state' to the props within the component:
function mapStateToProps(state) {
return {
users: state.users.items
};
}
和一个将调度的动作映射到作为props传递给组件的函数:
and one to map the dispatched actions to functions passed into the component as props:
function mapDispatchToProps(dispatch) {
return {
lockUser: (id) => dispatch(actions.lockUser(id)),
unlockUser: (id) => dispatch(actions.unlockUser(id)),
updateUser: (id, user) => dispatch(actions.updateUser(id, user)),
addUser: (user) => dispatch(actions.addUser(user))
};
}
然后使用连接将所有内容拉到一起/ code>方法:
This then all gets pulled together using the connect
method:
export default connect(mapStateToProps, mapDispatchToProps)(UsersContainer);
我觉得所有这一切都在附加取消订阅
组件的方法,但它确实简化了事情。
I have a feeling that all this does under the hood is attach the unsubscribe
method to the component but it does simplify things substantially.
这篇关于使用redux时,如何在反应组件中处理取消订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!