简体   繁体   中英

How to unsubscribe from redux store when component will unmount? How to decorate redux connect?

I am passing the following props (storeName) to my component:

<MyComponent reducerName="city" />

and I want to connect to store with a dynamic name (this.props.reducerName)

for example

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

How to decorate redux connect, or what i must to do?

I tried to skip redux connect and used store.subscribe

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

But when I move to another page, I see 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.

How to unsubscribe from redux store when component will unmount?

To unsubscribe you can simple execute the function return by store.subscribe :

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

connect has a second parameter of ownProps , which is an object containing all passed-in props. You would do something like this:

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

export default connect(mapStateToProps)(MyComponent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM