【问题标题】:react state array not updating反应状态数组不更新
【发布时间】:2020-03-29 20:09:34
【问题描述】:

我正在尝试使用新的以下数组更新我的状态,但是即使控制台没有显示任何错误并正确打印出应该形成的新数组,状态也不会更新以反映这一点。

我做错了什么?


state = {
    notes: [
      {
        text: "mow the lawn",
        author: "dean",
        time: "10am"
      },
      {
        text: "feed the dog",
        author: "sam",
        time: "2pm"
      }
    ]
  };


updateNotes = (title, name, eventTime) => {
    let newNote = {
      text: title,
      author: name,
      time: eventTime
    };
    this.setState(state => {
      const list = state.notes.concat(newNote);
      console.log(list); //shows the list formed correctly in the console
      return {
        list
      };
    });
  };

假设我在创建新笔记时输入了值、新文本、一些作者和下午 3 点,运行代码后我在控制台中看到的内容也可供参考


(3) [{…}, {…}, {…}]
0: {text: "mow the lawn", author: "dean", time: "10am"}
1: {text: "feed the dog", author: "sam", time: "2pm"}
2: {text: "new text", author: "some author", time: "3pm"}

【问题讨论】:

    标签: arrays reactjs state


    【解决方案1】:

    应该是:

    return {
      notes: list
    };
    

    您现在正在做的是向状态添加一个新变量list

    【讨论】:

    • 谢谢!第一次看到的时候我完全没有意识到,但现在很明显
    【解决方案2】:

    即使您的注释在名为 notes 的字段内,为什么还要更新名为 list 的字段?

    { list } 是创建一个对象的简写,该对象具有名为 list 的字段和存储在以相同方式命名的变量中的值。

    只需更新正确的字段:

    return {
        notes: list,
    };
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2016-01-19
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2020-01-13
      • 2020-02-02
      相关资源
      最近更新 更多