React-Redux:如何实际更新依赖于存储的其他值的redux存储的状态

时间:2020-06-11 05:13:15

标签: reactjs redux react-redux redux-store

我是使用React-Redux的新手。因此,在这种特殊情况下,我面临一些问题。我的Redux商店是这样的:

{
    info: {firstName: 'abc', lastName: 'xyz', email: abc.xyz@gmail.com, name: 'abc xyz', id: 145},
    userInfo: {firstName: 'abc', lastName: 'xyz', email: abc.xyz@gmail.com, contactNumber: 1234567890, country: 'India'}
}

现在,我从不同的页面收到这两个详细信息。我将它们存储在商店中,并使用react-redux进行API调用以更新商店数据。因此,我使用单独的API调用接收了这两个数据。现在,当我更新userInfo有效负载时,我可以成功更新我的userInfo存储状态。但是,firstName和lastName是2个通用字段。因此,每次更新userInfo时,最好的做法是更新信息,因为它们必须同步且相同。

粘贴一些redux代码以供参考:

reducer.js (有关信息)

import * as actionTypes from './actionTypes';

export const initialState = {
  email: null,
  firstName: null,
  id: null,
  lastName: null,
  name: null
};

export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SET_INFORMATION: {
      const { info = {} } = action;
      return { ...info };
    }
    default:
      return state;
  }
}

reducer.js (用于userInfo)

import * as actionTypes from './actionTypes';

export const initialState = {
    firstName: null,
    lastName: null,
    email: null,
    contactNumber: null,
    country: null
};

export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.USER_INFORMATION: {
      const { userInfo = {} } = action;
      return { ...state, ...userInfo };
    }
    case actionTypes.GET_USER_INFORMATION_ERROR:
    case actionTypes.PATCH_USER_INFORMATION_HEADER_ERROR: {
      const { error = {} } = action;
      return { ...error };
    }
    case actionTypes.PATCH_USER_INFORMATION_HEADER: {
      const { userInfo: { data = {} } = {} } = action;
      return { ...state, ...data };
    }
    default:
      return state;
  }
}

请以最佳实践帮助我,以便在每次更新另一个数据时都能同时更新这两个数据,以使数据保持同步。 TIA。

2 个答案:

答案 0 :(得分:1)

对于以减速器为中心的方法,请使用另一个减速器(作为包装器)来处理需要在减速器之间共享数据的情况,如下所示:

const combinedReducer = combineReducers({
    info: infoReducer,
    userInfo: userInfoReducer
});

function specialCaseReducerWrapper(state, action) {
    switch (action.type) {
        case "SOME_SPECIAL_ACTION": {
            return {
                // specifically pass state.userInfo as an additional argument
                info: infoReducer(state.info, action, state.userInfo),
                userInfo: userInfoReducer(state.userInfo, action)
            };
        }
        default:
            return state;
    }
}

function rootReducer(state, action) {
    const intermediateState = combinedReducer(state, action);
    const finalState = specialCaseReducerWrapper(intermediateState, action);
    return finalState;
}

作为参考,请选中Beyond combineReducers

答案 1 :(得分:1)

每次更新userInfo时,最好的做法是更新信息,因为它们必须同步且相同

最佳做法是从不保持重复数据的状态。您已经经历了很多尝试使其同步的事情,随着时间的流逝,它会变得更加糟糕。您很可能会遇到数据不同步的情况,而您或使用此代码的其他人可能只是忘记了在实施新更改后再次同步数据。这些错误也很难捕获

如果您在商店的各个部分之间拥有通用数据,则只需要保留一个实例