Handling undefined/null properties in components during first render

后端 未结 3 859
春和景丽
春和景丽 2021-01-13 01:28

I\'m learning react and it\'s great, but i\'ve ran into an issue and i\'m not sure what the best practice is to solve it.

I\'m fetching data from an API in my compon

3条回答
  •  甜味超标
    2021-01-13 01:51

    It Depends. suppose you are fetching books data from server. here is how to do that.

    state = {
      books: null,
    }
    

    if, your backend api is correctly setup. You will get either empty array for no books or array with some length

    componentDidMount(){
        getBooksFromServer().then(res => {
         this.setState({
         books: res.data
       })
      })
     }
    

    Now In Your render method

       render() {
             const { books } = this.state;
             let renderData;
             if(!books) {
              renderData = 
          } else
            if(books.length === 0) {
            renderData = 
           }
          else {
         renderData = 
       }
    
       return renderData;
       }  
    

    If you are using offline data persistence In that case initally you won't have emoty array.So This way of handling won't work. To show the spinner you have to keep a variable loader in state. and set it true before calling api and make it false when promise resolves or rejects.

    finally read upon to state.

       const {loader} = this.state;
       if(loader) {
       renderData = 
    }
    

提交回复
热议问题