How do I stop a component rendering before data is fetched?

前端 未结 3 1997
后悔当初
后悔当初 2021-02-04 17:03

Currently in react I have to functions in the componentDidMount lifecycle method in which call action creators to which fetch data. The component uses the data however, dependin

3条回答
  •  梦毁少年i
    2021-02-04 17:51

    In your constructor, declare a state variable to track if data is loaded. For example:

    constructor (props) {
      super(props)
      this.state = {
        dataLoaded: false
      }
    }
    

    Then in your render method, return null if this.state.dataLoaded is false:

    render () {
      const { dataLoaded } = this.state
      return (
        
    { dataLoaded && }
    ) }

    And in the methods you use to fetch data, make sure you call this.setState({ dataLoaded: true }) when data has been fetched

提交回复
热议问题