Can't set state in componentWillMount

前端 未结 2 982
情书的邮戳
情书的邮戳 2021-01-02 03:19

I am creating a simple chat app where I make an api call to my database via axios which returns an array of message objects. I am able to get the data when I make an axios c

2条回答
  •  -上瘾入骨i
    2021-01-02 03:34

    componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method. docs

    So, You need to call componentDidMount as-

    componentDidMount() {
        axios.get(`api/messages`)
          .then((result) => {
            const messages = result.data
            console.log("COMPONENT WILL Mount messages : ", messages);
            this.setState({ 
              messages: [ ...messages.content ] 
            })
      })
    

提交回复
热议问题