问题描述
创建商店后是否可以添加减速器?
示例: 假设我有这个React应用
//App.jsx
const reducers = {foo : []}
const store = createStore(combineReducers(reducers));
const App = () => <Provider store={store}><Test/></Provider>
//Test.jsx
class Test extends Component {
componentDidMount() {
//here I want to add new reducer to the store
//I will handle duplication problem
//I'm looking for something like this
store.appendReducer('REDUCER_KEY',someReducer);
}
...
}
export default connect()(Test)
我想知道这是否可行,如果可以的话如何实现。
我有一个主意,但这并不完美。我可以添加一个全局回调函数,并在根组件上侦听任何调用,然后在发生任何调用时重新创建存储。这样的问题将导致在任何减速器添加时重新渲染整个组件树。
解决方法
是的,可能有类似的事情
const newRootReducer = combineReducers({
existingSlice: existingSliceReducer,newSlice: newSliceReducer
})
store.replaceReducer(newRootReducer)
您可以检查DOC以获取更多信息redux DOC