代码之家  ›  专栏  ›  技术社区  ›  James Delaney

为什么在正确设置状态时不声明状态?

  •  0
  • James Delaney  · 技术社区  · 8 年前

     async componentDidMount() {
        const claimNumber = 'T1339838' 
        const { runtime } = this.context
        const data = await runtime.select('comments-get', { claimNumber : claimNumber})
    
        // THIS commentsData ARE empty
        this.setState = ({ commentsData: data, })
    
        console.log("COMENTS DATA: ", this.state.commentsData)
      }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Shubham Gupta    8 年前

    您设置的状态不正确。另外,setState是异步的,所以您可能希望将该控制台日志语句放在setState回调中。

    this.setState({ commentsData: data }, () => {
        console.log("COMENTS DATA: ", this.state.commentsData)
    })