如何解决还原,反应我无法推送到已经有数据的状态数组
我无法推送到 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,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)}
解决方法
使用展开运算符创建一个以 action.payload
作为最终元素的新数组:
return {
...state,fetchedSpendings: [...state.fetchedSpendings,action.payload],}
.push
修改数组并返回添加的元素,因此使用 fetchedSpendings
时 .push
不再是数组。另外,React 需要看到一个新的数组来更新。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。