gpt4 book ai didi

javascript - React Redux array.push 问题

转载 作者:行者123 更新时间:2023-11-30 11:30:07 25 4
gpt4 key购买 nike

我在尝试使用 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com