【问题标题】:React setState immutably in es6: cannot convert undefined or null to objectReact setState 在 es6 中不可变:无法将 undefined 或 null 转换为对象
【发布时间】:2018-10-23 21:08:43
【问题描述】:

我正在尝试使用状态不应该被改变的规则来设置状态,但我不断收到错误。想不通。

这是我的状态:

this.state = {
      jsonReturnedValue: null,
      fruit: [
        {
          id: 1,
          title: 'Orange',
          selected: false,
          key: 'fruit'
        },
        {
          id: 2,
          title: 'Grape',
          selected: false,
          key: 'fruit'
        },
        {
          id: 3,
          title: 'Pomegranate',
          selected: false,
          key: 'fruit'
        },
        {
          id: 4,
          title: 'Strawberry',
          selected: false,
          key: 'fruit'
        }
      ]
    }

当组件挂载时,我会执行 fetch:

  componentDidMount() {
    fetch('http://127.0.0.1:8000/api/printing/postcards-printing')
      .then(response => response.json())
      .then(json => {
        this.setState({ jsonReturnedValue: [...this.state.jsonReturnedValue, json.printCategory.products] }, () => console.log(this.state));
      });
  }

这会返回错误: Uncaught (in promise) TypeError: Cannot convert undefined or null to object

以下作品

  .then(json => {
    this.setState({ jsonReturnedValue: json.printCategory.products }, () => console.log(this.state));
  });

但是,根据我所读到的内容,工作人员会改变状态,这是一种不好的做法。任何帮助将不胜感激!

【问题讨论】:

  • 因为 `jsonReturnedValue: null,` 您的代码试图 [...null] 导致错误。所以要么初始化jsonReturnedValue: [],要么检查jsonReturnedValue是否还不是数组
  • 就是这样!现在我唯一的事情是我有 jsonReturnedValue->array[0]->array[3] 所以它将另一个数组添加到数组中。我怎样才能让它只是推动阵列? @skyboyer
  • [...this.state.jsonReturnedValue, ...json.printCategory.products]

标签: javascript reactjs


【解决方案1】:

您正在尝试传播一个空原语,这是不可能的。因此,请改为使用您的初始状态:

this.state = {
  jsonReturnedValue: [],
  fruit: [
    {
      id: 1,
      title: 'Orange',
      selected: false,
      key: 'fruit'
    },
    {
      id: 2,
      title: 'Grape',
      selected: false,
      key: 'fruit'
    },
    {
      id: 3,
      title: 'Pomegranate',
      selected: false,
      key: 'fruit'
    },
    {
      id: 4,
      title: 'Strawberry',
      selected: false,
      key: 'fruit'
    }
  ]
};

另请注意,您将要执行此操作{ jsonReturnedValue: [...this.state.jsonReturnedValue, ...json.printCategory.products] }。请注意数组第二个索引中的展开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 2019-10-25
    • 1970-01-01
    • 2021-07-29
    • 2020-07-19
    • 2020-12-06
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多