javascript - 使用 redux 时应该如何在 react 组件中处理取消订阅?

标签 javascript reactjs redux

在我的组件中,我有以下内容:

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/

相关文章:

javascript - React - 如何从长时间运行的操作将正确的 prop 传递给子组件

reactjs - 防止子元素不必要的重新渲染

html - 在 html 上更改 svg 图像背景颜色?

javascript - 关闭请求在对话框中不起作用

javascript - React、Redux、TypeError : undefined is not an object, if 语句

javascript - 使用换行符解析 json 并显示为 HTML

javascript - 类型错误 : Cannot read property 'style' of null in React App

javascript - 使 Google Annotated Timeline 为缺失日期填充零

javascript - 使用 redux 操作获取数据

javascript - 分配一个变量以及用另一个数组的项目迭代for循环