【问题标题】:React/Redux: state called twice? (concat(), not push())React/Redux:状态调用了两次? (连接(),而不是推())
【发布时间】:2016-11-03 22:48:31
【问题描述】:

我在将新的todo 添加到经典的todos 时遇到问题。在 React/Redux 上进行。

这里是reducer-todos.js

export default function (state=[
    {
        id: 0,
        todo: "Study English"
    },
    {
        id: 1,
        todo: "Run sprint"
    },
    {
        id: 2,
        todo: "Call Bob"
    }], action) {
    switch(action.type) {
        case "ADD_TODO":
            return state.push({id: state.length, todo: action.todo});
            break;
    }
    return state;
}

这是我得到的问题:

不知何故,todos 对象变成了4,而不是 Array[4]。为什么会这样?

如果需要更多信息,请告诉我。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    不知何故 todos 对象变成了 4,而不是 Array[4]。为什么会这样?

    您正在使用push,它将返回其新大小。改用concat,它将返回一个新数组,其中添加了您的新项目而不会发生变异。

    所以这个:

    return state.push({id: state.length, todo: action.todo});
    

    应该变成:

    return state.concat({id: state.length, todo: action.todo});
    

    【讨论】:

    • @SamKirklandWA 不客气!单击答案旁边的复选标记以接受它,以便其他人知道您的问题已解决。
    • 会的,等 3 分钟过去。 )
    • 嗨@Jack,很抱歉打扰你,但是当我尝试从 JSON 对象中删除一个元素时,splice() 也会运行两次并删除几乎所有内容。是否也有替代方案?
    • @SamKirklandWA 不要使用splice 使用slice。在这里查看我的答案:stackoverflow.com/questions/40294652/…
    • 感谢杰克的帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2023-04-02
    • 2021-11-02
    • 2016-02-22
    • 1970-01-01
    • 2019-11-10
    • 2020-11-10
    相关资源
    最近更新 更多