我将以下道具(storeName)传递给我的组件:
<MyComponent reducerName="city" />
我想用动态名称(this.props.reducerName)连接到商店
例如
export default connect(state => ({
some: state[this.props.reducerName]
}), { })(MyComponent);
如何装饰redux connect,或者我必须做什么?
我尝试跳过redux connect并使用了store.subscribe
componentDidMount() {
store.subscribe(() => {
this.setState({some: store.getState([this.props.reducerName]});
});
}
但是当我移动到另一个页面时,我看到以下错误:
警告:setState(...):只能更新已安装或已安装 零件。这通常意味着您在已卸载时调用了setState() 零件。这是一个无操作。
如何在卸载组件时取消订阅redux store?
答案 0 :(得分:44)
要取消订阅,您可以通过store.subscribe
简单地执行函数返回:
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
// ...
});
}
componentWillUnmount() {
this.unsubscribe();
}
答案 1 :(得分:4)
connect
有第二个参数ownProps
,它是一个包含所有传入道具的对象。你会做这样的事情:
const mapStateToProps = (state, { reducerName = 'defaultReducer' }) => ({
some: state[reducerName],
});
export default connect(mapStateToProps)(MyComponent);