[英]Working of push in react while using redux to update the state
以下代碼是我的減速器的代碼,我在容器中調用這些 function
const intialState = {
counter: 0,
results: []
};
const reducer = (state = intialState, action) => {
switch (action.type) {
case "INCREMENT":
return {
...state,
counter: state.counter + 1
};
case "STORE_RESULT": {
return {
...state,
results: state.results.push(state.counter)
};
}
}
return state;
};
export default reducer;
我收到以下錯誤
TypeError: state.results.push is not a function
reducer
1) 我在我的項目中使用 redux 減速機
2) 我正在更新 state,方法是將調度中的類型傳遞到我的容器中
3)我試圖通過推送來更新數組(我知道它返回長度)但我想知道它為什么不工作
4)按照我在 javascript 中嘗試的代碼,一切正常
var a = {
b:[]
}
a.b.push(11)
//output
1
push
返回變異array
的新length
。 使用concat
代替它返回一個新數組
results : state.results.concat(item)
讓我們假設以下代碼
results : state.results.push('foo')
假設results
的length
為5
,上面的代碼將斷言
results : 5
下次您嘗試push
results
時,這將是您的編譯器的樣子
5.push('foo')
您應該在減速器開關中添加默認情況。
並使用[...state.results, state.counter]
代替state.results.push(state.counter)
。
像這樣
const intialState = {
counter: 0,
results: []
};
const reducer = (state = intialState, action) => {
switch (action.type) {
case "INCREMENT":
return {
...state,
counter: state.counter + 1
};
case "STORE_RESULT": {
return {
...state,
results: [...state.results, state.counter] // here
};
default:
return state; // here
}
}
};
export default reducer;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.