【问题标题】:Issue with React Redux array.pushReact Redux array.push 的问题
【发布时间】: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;
      }
    }

【问题讨论】:

标签: javascript arrays reactjs redux


【解决方案1】:

这是因为 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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2021-07-19
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多