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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With