Can I call APIs in componentWillMount in React?

前端 未结 3 885
遥遥无期
遥遥无期 2020-12-03 00:15

I\'m working on react for last 1 year. The convention which we follow is make an API call in componentDidMount, fetch the data and setState after the data has c

3条回答
  •  佛祖请我去吃肉
    2020-12-03 00:41

    1. componentWillMount and re-rendering

    Compare this two componentWillMount methods.
    One causes additional re-render, one does not

    componentWillMount () {
      // This will not cause additional re-render
      this.setState({ name: 'Andrej '});
    }
    
    componentWillMount () {
      fetch('http://whatever/profile').then(() => {
        // This in the other hand will cause additional rerender,
        // since fetch is async and state is set after request completes.
        this.setState({ name: 'Andrej '});
      })
    }
    

    .
    .
    .
    2. Where to invoke API calls?

    componentWillMount () {
      // Is triggered on server and on client as well.
      // Server won't wait for completion though, nor will be able to trigger re-render
      // for client.
      fetch('...')
    }
    
    componentDidMount () {
      // Is triggered on client, but never on server.
      // This is a good place to invoke API calls.
      fetch('...')
    } 
    

    If you are rendering on server and your component does need data for rendering, you should fetch (and wait for completion) outside of component and pass data thru props and render component to string afterwards.

提交回复
热议问题