【问题标题】:setState not updating the array in reactsetState 没有在反应中更新数组
【发布时间】:2021-10-31 23:30:43
【问题描述】:

我正在开发一个反应应用程序,我必须更改数组中对象的键。这是我的代码:

getInterfaces(){
    //assign a array to interfaceOption state
    let interfaceOptions=[
      {
        "interface_name": "ORU",
        "interface_id": "1"
      },
      {
        "interface_name": "MLM",
        "interface_id": "2"
      },
    ]
   
    //change interfaceOptions keys to title and value
    let interfaceOptionsWithTitle = interfaceOptions.map(function(item){
      return {
        title: item.interface_name,
        value: item.interface_id
      }
    })
    console.log(interfaceOptionsWithTitle)
    this.setState({
      interfaceOptions: interfaceOptionsWithTitle
    })
  
    //print updated interfaceOptions
    console.log(this.state.interfaceOptions)

  }

这里我最初分配了一个数组,然后我更改了它的键并使用 console.log 打印它并打印更新的数组但是当我再次 setState 数组和控制台记录它时,它返回一个空数组。有人可以帮忙我明白这个吗?

如果我想更新 interfaceOptions,这会起作用吗?

this.state.interfaceOptions = this.state.interfaceOptions.map(item => {
      return {
        title: item.interface_name,
        value: item.interface_id
      };
    });

谢谢

【问题讨论】:

  • 请查看answer
  • setState 是一个异步函数,使用回调来打印我们放在 getInterfaces 之外的 console.log

标签: javascript arrays reactjs react-hooks setstate


【解决方案1】:

因为状态只有在组件重新渲染时才有新值。所以只需将 console.log 放到外部函数getInterfaces 即可查看新值

getInterfaces(){
...
}
console.log(this.state.interfaceOptions)

【讨论】:

    【解决方案2】:

    setState 本质上是异步的,您尝试更新该值并在下一行打印它,这将始终为您提供旧状态值,因为在浏览器尝试打印该值时,状态未更新,它需要一些时间来更新值。

    如果您想打印更新后的状态值,您需要将回调函数传递给 setState 并打印该值 例如

        this.setState({
          interfaceOptions: interfaceOptionsWithTitle
        },() => {
         console.log(this.state.interfaceOptions)
        })
    

    注意:上述setState中的回调函数会在渲染完成后执行。

    【讨论】:

    • 你也可以检查问题的第二部分吗?
    • @rudeTool 这不是推荐的方式,它会更新值但不会触发重新渲染
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2018-11-23
    • 1970-01-01
    • 2021-04-19
    • 2021-03-23
    • 2023-03-07
    相关资源
    最近更新 更多