本文介绍了使用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:

我想知道的是我应该分配取消订阅这个还是有更好的地方分配它?

What I'd like to know is should I be assigning unsubscribe to this or is there a better place to assign it?

推荐答案

正如在评论中提到的那样,我最终使用。

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时,如何在反应组件中处理取消订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:25