当我尝试使用 .push(newvalue) 更新存储中的数组时,我遇到了一个问题。当我推送新值时,状态将从数组更新为数组长度的值。
更新前的状态:['asd', 'sdf', 'wer']
之后的状态:4
行动:
export function updateLocalCompliments(newCompliment) {
return ({
type: LOCAL_COMPLIMENT,
payload: newCompliment
})
}
reducer:(state.compliments 是实际的数组)
const INITIAL_STATE = {
compliments: []
}
function compliments(state=INITIAL_STATE, action) {
switch (action.type) {
case LOCAL_COMPLIMENT:
return (
Object.assign({}, state, {
compliments: state.compliments.push(action.payload)
})
)
default:
return state;
}
}
最佳答案
这是因为push方法修改了它所调用的数组并返回新的长度。你想要的是像 concat() 这样的东西。
推送:https://www.w3schools.com/jsref/jsref_push.asp
连接:https://www.w3schools.com/jsref/jsref_concat_array.asp
compliments: state.compliments.concat(action.payload)
关于javascript - React Redux array.push 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571422/