简体   繁体   English

具有相同 redux 反应组件的多个实例

[英]having multiple instance of same redux react components

I am building a react app with multi-widgets using react-redux every widget created dynamically.我正在使用 react-redux 使用动态创建的每个小部件构建一个带有多小部件的反应应用程序。

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索引.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:您可以为每个小部件动态减速器是通过为每个新创建的小部件分配唯一的 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
});

Then have a widget id for every action specific to each widget:然后为每个小部件特定的每个操作设置一个小部件 ID:

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'
      },
      ...
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM