【发布时间】:2018-03-16 05:37:40
【问题描述】:
当我尝试使用 .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不返回变异数组,而是返回其更新后的长度。您需要以不同的方式处理此问题:developer.mozilla.org/de/docs/Web/JavaScript/Reference/… -
push不应该与 react-redux 一起使用,因为它会改变数组
标签: javascript arrays reactjs redux