setState 没有更新反应中的数组

setState not updating the array in react

我正在开发一个反应应用程序,我必须在 array.Here 我的代码中更改对象的键:

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 打印它并打印更新的数组但是当我设置数组并再次在控制台记录它时,它 returns 一个空 array.Can 有人帮我理解这个吗?

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

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

谢谢

因为状态只有在组件重新渲染时才有新的值。所以只要把 console.log 放到外部函数 getInterfaces 就可以看到新值

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

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

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

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

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