簡體   English   中英

React-Redux:如何更改減速機 function 中的初始 state

[英]React-Redux: How to change the initial state in Reducer function

我正在開發一個 React 應用程序,我正在使用 Redux 來存儲 state。 我有以下代碼:

menu.reducer.js:

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

const INITIAL_STATE = []

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

menu.actions.js:

import { apiUrl, apiConfig } from '../../util/api';
import { 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 })
    }
}

在上面的Reducer中,初始的state是一個空數組。 調度GET_MENU操作,更改初始 state 以便它包含菜單項數組。

GET_MENU操作中獲取的數組如下:

在此處輸入圖像描述

但是我希望我的初始 state 如下所示:

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

在 reducer 代碼中的GET_MENU案例中,我不確定使用什么正確的語法來將 state 中的 menuArray 屬性分配給從GET_MENU操作返回的數組。

任何見解都值得贊賞。

state 只是一個 JavaScript 值。 如果您希望它是具有兩個屬性的 object,那么這不是正確的語法:

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

這是:

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

你的 reducer 現在還需要返回對象。 您每次都需要返回一個的 object。 以下是你如何做你的減速器,特別是:

import { 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] };
        default:
            return state;
    }
}

這表示“創建一個包含先前 state 的所有屬性但將menuArray屬性設置為有效負載的 object。”

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

const initialState= {
menuArray: [],
isSending: false
}

export default (state = initialState, action) => {
    switch (action.type) {
        case GET_MENU:
            return {...state, menuArray: action.payload};
        default:
            return state;
    }
}
import { 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
      };
    default:
      return state;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM