![](/img/trans.png)
[英]having multiple instance of same reusable redux react components on the same page/route
[英]having multiple instance of same redux react components
我正在使用 react-redux 使用动态创建的每个小部件构建一个带有多小部件的反应应用程序。
当小部件中的更新反映在所有其他小部件中时,我遇到了问题。
有没有办法处理多个减速器来处理每个小部件的隔离数据?
减速器
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
}
}
}
索引.js
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers'
const store = createStore(reducers)
<Provider store={store}><Widget /></Provider>
您可以为每个小部件动态减速器是通过为每个新创建的小部件分配唯一的 id 并创建一个新的父减速器作为包装器,例如:
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'
},
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.