Can't set state in componentWillMount

前端 未结 2 981
情书的邮戳
情书的邮戳 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条回答
  • 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 ] 
            })
      })
    
    0 讨论(0)
  • 2021-01-02 03:52

    In your case, your setState() won't work because you're using setState() inside an async callback

    Working Fiddle: https://jsfiddle.net/xytma20g/3/

    You're making an API call which is async. So, the setState will be invoke only after receiving the data. It does not do anything with componentWillMount or componentDidMount. You need to handle the empty message in your render. When you receive your data from the API, set that data to the state and component will re-render with the new state which will be reflected in your render.

    Pseudo code:

    export default class Chat extends Component {
      constructor(props){
        super(props);
    
        this.state = {
          messages : [],
          message : '',
        };
        this.socket = io('/api/');
        this.onSubmitMessage = this.onSubmitMessage.bind(this);
        this.onInputChange = this.onInputChange.bind(this);
      }
    
      componentWillMount() {
        axios.get(`api/messages`)
          .then((result) => {
            const messages = result.data
            console.log("COMPONENT WILL Mount messages : ", messages);
            this.setState({ 
              messages: [ ...messages.content ] 
            })
      })
    
      render(){
        if(this.state.messages.length === 0){
         return false //return false or a <Loader/> when you don't have anything in your message[]
        }
    
       //rest of your render.
      }
    }; 
    
    0 讨论(0)
提交回复
热议问题