【问题标题】:React-Redux: Assigning a modified array to a property in the stateReact-Redux:将修改后的数组分配给状态中的属性
【发布时间】:2020-04-23 05:54:07
【问题描述】:

我正在开发一个 React 应用程序,我正在使用 Redux 来存储状态。我有以下代码:

menu.actions.js:

import { apiUrl, apiConfig } from '../../util/api';
import { ADD_CATEGORY, GET_MENU } from './menu.types';

export const getMenu = () => async dispatch => {
    const response = await fetch(`${apiUrl}/menu`);
    if (response.ok) {
        const menuData = await response.json();
        dispatch({ type: GET_MENU, payload: menuData })
    }
}

export const addCategory = category => async dispatch => {
    const options = {
        ...apiConfig(),
        method: 'POST',
        body: JSON.stringify(category)
    };
    const response = await fetch(apiUrl + '/category/', options)
    let data = await response.json()
    if (response.ok) {
        dispatch({ type: ADD_CATEGORY, payload: { ...data } })
    } else {
        alert(data.error)
    }
}

menu.reducer.js:

import { ADD_CATEGORY, GET_MENU } from './menu.types';

const INITIAL_STATE = []

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case GET_MENU:
            return [...action.payload];
        case ADD_CATEGORY:
            return [ ...state, { ...action.payload, menuItem: [] } ]
        default:
            return state;
    }
}

在上面的Reducer中,初始状态是一个空数组。调度 GET_MENU 操作,更改初始状态,使其包含菜单项数组。

在 GET_MENU 操作中获取的数组如下:

我已经修改了 Reducer 函数中的代码,现在初始状态如下:

menu.reducernew.js:

import { ADD_CATEGORY, GET_MENU } from './menu.types';

    const INITIAL_STATE = {
        menuArray: [],
        isSending: false
    };

    export default (state = INITIAL_STATE, action) => {
        switch (action.type) {
            case GET_MENU:
                return {
                ...state,
                menuArray: action.payload
            };
            case ADD_CATEGORY:
                return {
                ...state,
                menuArray: [ ...menuArray, { ...action.payload, menuItem: [] } ]
            };

            default:
                return state;
        }
    }

对于 Reducer 中的 ADD_CATEGORY 情况,我不确定将状态中的 menuArray 属性重新分配给修改后的数组的正确语法是什么。我希望数组将在 addCategory 动作创建者中获取的新对象添加到其中。

当我运行我的应用程序时,我收到以下错误:

我不确定为什么会收到此错误或如何解决它。任何见解都值得赞赏。

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    此处menuArray: [ ...menuArray, { ...action.payload, menuItem: [] } menuArray 变量未定义您要传播的变量。使用state.menuArray 访问当前的menuArray

    变化:

    menuArray: [ ...menuArray, { ...action.payload, menuItem: [] }

    收件人:

    menuArray: [ ...state.menuArray, { ...action.payload, menuItem: [] }

    case ADD_CATEGORY:
         return {
              ...state,
            menuArray: [ ...state.menuArray, { ...action.payload, menuItem: [] } ]
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多