在 redux 中调度多个动作会复制状态参数

Dispatching multiple actions in redux duplicates the state parameters

我已经使用创建了两个动作及其各自的减速器。当我调度任何单个动作时,两个动作的初始状态都被保存到状态参数重复的状态。

actions/index.js

import { COUNTER_CHANGE, UPDATE_NAVIGATION } from "../constants";

export function changeCount(count) {

  return {
    type: COUNTER_CHANGE,
    payload: count,
  };
}

export function updateNavigation(obj) {

  return {
    type: UPDATE_NAVIGATION,
    payload: obj,
  };
}

reducers.js

import { COUNTER_CHANGE, UPDATE_NAVIGATION } from "../constants";
import logger from "redux-logger";

const initialState = {
  count: 0,
  navigation: {},
};

export const countReducer = (state = initialState, action) => {

  switch (action.type) {
    case COUNTER_CHANGE:
      return {
        ...state,
        count: action.payload,
      };

    default:
      return state;
  }
};

export const updateNavigation = (state = initialState, action) => {

  switch (action.type) {
    case UPDATE_NAVIGATION:
      return {
        ...state,
        navigation: action.payload,
      };
    default:
      return state;
  }
};
// export default countReducer;

reducer/index.js

import { countReducer, updateNavigation } from "../reducers/countReducer";
import { combineReducers } from "redux";

const allReducers = combineReducers({
  countReducer,
  updateNavigation,
});

export default allReducers;

调度操作

componentDidMount = () => {
    const { navigation } = this.props;
    this.props.updateNavigation(navigation);
};

const mapDispatchToProps = (dispatch) => {
  return { ...bindActionCreators({ changeCount, updateNavigation }, dispatch) };
};

正如我们在这里看到的,我只触发了 updateNavigation 操作。但它会在 redux 状态中使用重复参数更新状态,如下所示

预期的 o/p 将是

countReducer:{计数:0} 更新导航:{导航:{}}

每个减速器的状态形状不正确。请参阅 defining-state-shape 文档并试试这个:

export const countReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case COUNTER_CHANGE:
      return {
        ...state,
        count: action.payload,
      };

    default:
      return state;
  }
};

export const updateNavigation = (state = { navigation: {} }, action) => {
  switch (action.type) {
    case UPDATE_NAVIGATION:
      return {
        ...state,
        navigation: action.payload,
      };
    default:
      return state;
  }
};
import { countReducer, updateNavigation } from "../reducers/countReducer";
import { combineReducers } from "redux";

const allReducers = combineReducers({
  countReducer,
  updateNavigation,
});

const store = createStore(allReducers);
console.log(store.getState()); 

输出:

{ countReducer: { count: 0 }, updateNavigation: { navigation: {} } }

在你的action/index.js

import { COUNTER_CHANGE, UPDATE_NAVIGATION } from "../constants";

export function changeCount(count) {

  dispatch( {
    type: COUNTER_CHANGE,
    payload: count,
  });
}

export function updateNavigation(obj) {

  dispatch({
    type: UPDATE_NAVIGATION,
    payload: obj,
  });
}

发送数据而不返回数据