How should unsubscribe be handled in a react component when using redux?

百般思念 提交于 2019-12-19 06:51:08

问题


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();
},

Not calling unsubscribe causes the following error:

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?


回答1:


As mentioned by Salehen Rahman above in the comments I did end up using react-redux.

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
  };
}

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))
  };
}

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.



来源:https://stackoverflow.com/questions/32372646/how-should-unsubscribe-be-handled-in-a-react-component-when-using-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!