Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
Nemo Free Avatar asked Jun 17 '17 16:06

Nemo Free


2 Answers

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

componentDidMount() {
  this.unsubscribe = store.subscribe(() => {
    // ...
  });
}
componentWillUnmount() {
  this.unsubscribe();
}
like image 116
kkkkkkk Avatar answered Oct 27 '22 19:10

kkkkkkk


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);
like image 39
corvid Avatar answered Oct 27 '22 19:10

corvid