I am building a react app with multi-widgets using react-redux every widget created dynamically.
I have an issue when update in the widget reflect in all other widgets.
is there any way to handle multi reducer to handle isolated data for every widget?
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
});
Actions
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>
You can dynamic reducer for each widget is by assigning unique id for each new widget created and creating a new parent reducers as wrapper, something like:
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
});
Then have a widget id for every action specific to each widget:
export const SetAPI = (widgetId, data) => {
return {
type: "SET_API",
payload: {
API: data,
id: widgetId
}
}
}
Your resulting reducer will look something like this:
{
widgets: {
widget-1: {
API: 'api-1'
},
widget-2: {
API: 'api-2'
},
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.