我正在构建一个包含多个小部件的react应用程序,使用react redux动态创建每个小部件。
当小部件中的更新反映在所有其他小部件中时,我遇到了一个问题。
有什么方法可以处理多个reducer来处理每个小部件的隔离数据吗?
还原剂
import { combineReducers } from 'redux';
const widgetReducer= (state = {}, action) => {
switch (action.type) {
case 'SET_API':
return { ...state, API: action.payload.API };
}
return state;
}
export default combineReducers({
widget: widgetReducer
});
行动
export const SetAPI = (data) => {
return {
type: "SET_API",
payload: {
API: data
}
}
}
index.js
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers'
const store = createStore(reducers)
<Provider store={store}><Widget /></Provider>
您可以为每个小部件动态reducer,方法是为创建的每个新小部件分配唯一的id,并创建一个新的父级reducer作为包装器,类似于:
import { combineReducers } from 'redux';
const widgetReducer= (state = {}, action) => {
switch (action.type) {
case 'SET_API':
return { ...state, API: action.payload.API };
}
return state;
}
export widgetsContainerReducer(state = {}, action) {
switch(action.type) {
case 'SET_API':
case 'WIDGET_ACTION_1':
case 'WIDGET_ACTION_2': // other widget specific actions
const widgetId = action.payload.id;
return {
...state,
[widgetId]: widgetReducer(state[widgetId], action)
}}
default:
return state;
}
}
export default combineReducers({
widgets: widgetsContainerReducer
});
然后为每个小部件特定的每个操作都有一个小部件id:
export const SetAPI = (widgetId, data) => {
return {
type: "SET_API",
payload: {
API: data,
id: widgetId
}
}
}
你得到的减速器看起来像这样:
{
widgets: {
widget-1: {
API: 'api-1'
},
widget-2: {
API: 'api-2'
},
...
}
}