admin管理员组

文章数量:1289828

In my ponent I have the following:

ponentWillMount: function () {
  this.unsubscribe = store.subscribe(function () {
    this.setState({message: store.getState().authentication.message});
  }.bind(this));
},

ponentWillUnmount: function () {
  this.unsubscribe();
},

Not calling unsubscribe causes the following error:

Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. 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?

In my ponent I have the following:

ponentWillMount: function () {
  this.unsubscribe = store.subscribe(function () {
    this.setState({message: store.getState().authentication.message});
  }.bind(this));
},

ponentWillUnmount: function () {
  this.unsubscribe();
},

Not calling unsubscribe causes the following error:

Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. 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?

Share Improve this question asked Sep 3, 2015 at 10:04 ClarkieClarkie 7,5509 gold badges40 silver badges53 bronze badges 4
  • You should try in ponentDidMount() instead of ponentWillMount(). – collardeau Commented Sep 3, 2015 at 10:39
  • @legolandbridge that doesn't make any difference as I still need to unsubscribe. – Clarkie Commented Sep 3, 2015 at 10:49
  • Have you looked into using react-redux's connect and Provider? – Sal Rahman Commented Sep 6, 2015 at 18:01
  • 1 And assigning to this is perfectly fine. I have a bias against it, though, but that doesn't change the fact that, with React, it's perfectly fine. – Sal Rahman Commented Sep 6, 2015 at 18:02
Add a ment  | 

1 Answer 1

Reset to default 7

As mentioned by Salehen Rahman above in the ments 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 ponent:

function mapStateToProps(state) {
  return {
    users: state.users.items
  };
}

and one to map the dispatched actions to functions passed into the ponent 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 ponent but it does simplify things substantially.

本文标签: javascriptHow should unsubscribe be handled in a react component when using reduxStack Overflow