在我的组件中,我有以下内容:
componentWillMount: function () {
this.unsubscribe = store.subscribe(function () {
this.setState({message: store.getState().authentication.message});
}.bind(this));
},
componentWillUnmount: function () {
this.unsubscribe();
},
不调用取消订阅会导致以下错误:
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.
我想知道的是,我应该将 unsubscribe
分配给 this
还是有更好的分配位置?
最佳答案
如 Salehen Rahman 所述在上面的评论中我最终使用了 react-redux .
根据他们的文档,我创建了两个函数,一个用于将“全局状态”映射到组件中的 Prop :
function mapStateToProps(state) {
return {
users: state.users.items
};
}
还有一个用于将分派(dispatch)的操作映射到作为 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))
};
}
然后使用 connect
方法将所有这些整合在一起:
export default connect(mapStateToProps, mapDispatchToProps)(UsersContainer);
我有一种感觉,所有这些在幕后所做的就是将 unsubscribe
方法附加到组件,但它确实大大简化了事情。
关于javascript - 使用 redux 时应该如何在 react 组件中处理取消订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32372646/