![](/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.