How to unsubscribe from redux store when the component disconnects? How to decorate redux connection?

I pass the following attribute (storeName) to my component:

<MyComponent reducerName="city" />

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

eg

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

How to decorate redux connection or what should I do?

I tried to skip the redux connection and use store.subscribe

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

But when I go to another page, I see the following error:

Warning: setState (...): can only update an installed or mounted component. This usually means that you called setState () on an unmounted component. This is a no-op.

How to unsubscribe from redux store when the component disconnects?

+4
2

connect ownProps, , . - :

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

export default connect(mapStateToProps)(MyComponent);
+3

, store.subscribe:

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

Source: https://habr.com/ru/post/1679521/


All Articles