首页 文章

如何在组件卸载时取消订阅redux store?如何装饰redux连接?

提问于
浏览
8

我将以下道具(storeName)传递给我的组件:

<MyComponent reducerName="city" />

我想用动态名称连接到商店(this.props.reducerName)

例如

export default connect(state => ({
    some: state[this.props.reducerName]
}), { })(MyComponent);

如何装饰redux连接,或者我必须做什么?

我试图跳过redux connect并使用store.subscribe

componentDidMount() {
    store.subscribe(() => {
        this.setState({some: store.getState([this.props.reducerName]});
    });
}

但是当我移动到另一个页面时,我看到以下错误:

警告:setState(...):只能更新已安装或安装的组件 . 这通常意味着您在已卸载的组件上调用了setState() . 这是一个无操作 .

如何在组件卸载时取消订阅redux store?

2 回答

  • 41

    要取消订阅,您可以通过 store.subscribe 简单地执行函数返回:

    componentDidMount() {
      this.unsubscribe = store.subscribe(() => {
        // ...
      });
    }
    componentWillUnmount() {
      this.unsubscribe();
    }
    
  • 4

    connect 有第二个参数 ownProps ,它是一个包含所有传入道具的对象 . 你会做这样的事情:

    const mapStateToProps = (state, { reducerName = 'defaultReducer' }) => ({
      some: state[reducerName],
    });
    
    export default connect(mapStateToProps)(MyComponent);
    

相关问题