ReactJS:在状态对象上设置状态

时间:2021-05-03 09:20:04

标签: javascript reactjs

我的状态:

state = {
  validationButton: {
   button1: false
   }
}


componentDidMount(){
//....
this.check(1)
this.check(2)
}

check(Number){
 let today = new Date()
 // I call my api to see if exists document with the number
  db.get(`${Number}:${today}`)
  .then( (doc) => {
    //after that I found document:
    // * this is what I would to do *
    this.setState((this.state.validationButton[`button${Number}`] = true))
})
}

但我收到错误消息:

<块引用>

Invariant Violation:setState(...):需要一个状态变量对象来更新或一个函数返回一个状态变量对象。

如何设置为true?

2 个答案:

答案 0 :(得分:1)

setState 应该得到一个要设置的对象:

this.setState({ validationButton: {[`button${Number}`]: true });

答案 1 :(得分:1)

我相信你能做到:

this.setState({ validationButton: {[`button${Number}`]: true });
相关问题