// 初始化state
state = {personArr:[{name:'张三',id:1},{name:'李四',id:2},{name:'王五',id:3}]
}componentDidMount(){const newName = '赵六'const indexUpdate = 1const newArr = this.state.personArr.map((item,index)=>{if(indexUpdate === index){return {...item,name:newName}}else{return {...item}}})this.setState({personArr:newArr})console.log('personArr',this.state.personArr)
}
打印的值:
问题来了,明明已经修改过了,为什么拿不到值呢,原来是setState的执行机制导致的,setState是作为异步来执行的,打印是同步的,因此拿不到值
解决: 要想获取更新后的值,只需在setState第二个参数中获取即可
this.setState({personArr:newArr
},()=>{console.log('personArr',this.state.personArr)
})
打印结果:
完美解决!