开发者问题收集

redux,react。我无法推送到已经有数据的状态数组

2021-01-09
2077

我无法推送到 fetchedSpendings 状态数组,该数组在获取后已经有数据。

Reducer.js

import {FETCH_SPENDINGS, PUSH_SPENDING } from './types'

const initialState = {
    fetchedSpendings: []
}

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

    switch(action.type){


        case PUSH_SPENDING:

             return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}

            //return {...state, fetchedSpendings: state.fetchedSpendings = [action.payload]}



        case FETCH_SPENDINGS:
            
            return { ...state, fetchedSpendings: action.payload }

        default: return state
    }

}

注释掉此行以防 PUSH_SPENDING 正常工作,但它不会将数据添加到已包含对象的数组中,而是替换它们。

//return {...state, fetchedSpendings: state.fetchedSpendings = [action.payload]}

在这种情况下,另一个则没有。

 return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}

actions.js

export function fetchSpendings(){
    return async dispatch => {

        const userid = userDataGetter();

        try{
            const response = await axios.post('/api/getSpendings', { userID: userid})
            const json = await response["data"];

            dispatch( {type: FETCH_SPENDINGS, payload: json})
              console.log('Returned data:', json);
         } catch (e) {
         console.log(`Axios request failed in fetchSpendings: ${e}`);
         } 
     }
}


export function pushSpending(cost, category, note){
    return async dispatch => {

        const userData = userDataGetter();
        const userID = userData.userId;


        const dataSpend = {
        _id: userID, 
        date: String(new Date()),
        cost: cost, 
        category: category, 
        note: note
        }


        try{
            const response = await axios.post('/api/addSpending', {cost, category, note, userID})
            const json = await response;


            dispatch( {type: PUSH_SPENDING, payload: dataSpend})

        } catch(e){
        console.log(`Axios request failed in pushSpendings: ${e}`);

        M.toast({html: "incorrectly entered data"});

        }
    }
}

在 react 中我收到错误。props.Spending.map 不是一个函数。

因为这一行没有将数据推送到数组中。

return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}
1个回答

使用展开运算符创建一个新数组,其中 action.payload 作为其最终元素:

return {
  ...state,
  fetchedSpendings: [...state.fetchedSpendings, action.payload],
}

.push 修改数组并返回添加的元素,因此当您使用 .push 时, fetchedSpendings 不再是一个数组。此外,React 需要查看要更新的新数组。

Ross Allen
2021-01-09