Javascript 雷杜,反应。我能';t推送到已经有数据的状态数组
我无法推送到fetchedSpendings状态数组,该数组在获取后已经有数据 Reducer.jsJavascript 雷杜,反应。我能';t推送到已经有数据的状态数组,javascript,arrays,reactjs,redux,javascript-objects,Javascript,Arrays,Reactjs,Redux,Javascript Objects,我无法推送到fetchedSpendings状态数组,该数组在获取后已经有数据 Reducer.js import {FETCH_SPENDINGS, PUSH_SPENDING } from './types' const initialState = { fetchedSpendings: [] } export const dataReducer = (state = initialState, action) => { switch(action.type){
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_开销正常,但它不会将数据添加到已包含对象的数组中,而是替换它们
//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"});
}
}
}
我的反应是错误的。props.Spending.map不是一个函数
因为此行不能在数组中推送数据
return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}
使用spread操作符创建一个新数组,并将
action.payload
作为其最终元素:
return {
...state,
fetchedSpendings: [...state.fetchedSpendings, action.payload],
}
.push
修改数组并返回添加的元素,因此使用.push
时,fetchedSpendings
不再是数组。此外,React需要查看要更新的新阵列