简体   繁体   English

对象属性的setState数组反应失败,映射为es6

[英]react setState array of object property failed with map es6

Trying to update a state of a array of object but somehow it doesn't reflect in the state. 尝试更新对象数组的状态,但不知何故不能反映该状态。

set_is_core = (selected_id) => {

  const { main } = this.state

  const next_main = main.map(o => {
    if(o.main_id === selected_id){
      console('trigger') //true
      return ({
        ...o,
        is_core: true
      })
    }
    return o
  })

  this.setState({
    main: next_main
  }, ()=> console.log(this.state.main.some(o => o.is_core))//false?)
}

Couldn't figure out what is wrong. 无法找出问题所在。

You are trying to map over an object. 您正在尝试映射对象。 Only arrays can be mapped over using es6. 使用es6只能映射阵列。 You can either change your main variable structure to be an array or use lodash map which will allow you map over an object https://lodash.com/docs#map 您可以将main变量结构更改为数组,也可以使用lodash映射,这将允许您映射到对象https://lodash.com/docs#map

Something like this for example: 例如:

import {map} from 'lodash'

...

set_is_core = (selected_id) => {

  const { main } = this.state

  const next_main = map(main, (o) => {
    if(o.main_id === selected_id){
      console('trigger') //true
      return ({
        ...o,
        is_core: true
      })
    }
    return o
  })

  this.setState({
    main: next_main
  }, ()=> console.log(this.state.main.some(o => o.is_core))//false?)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM