React : How to Show Message if there is no records

前端 未结 5 1074
耶瑟儿~
耶瑟儿~ 2021-01-16 18:35

I am working on project in ReactJS, I am fetching data from server through API. I did some search filtration, I want to display message if there is no records available? I a

相关标签:
5条回答
  • 2021-01-16 19:12

    You can add your message as another conditional wherever you'd like:

    {this.state.filtered.length === 0 && (
      <div>Your Message</div>
    )}
    

    Or if you're trying to add a message for getting no results at all, then:

    {this.state.allData.length === 0 && (
      <div>Your Message</div>
    )}
    
    0 讨论(0)
  • 2021-01-16 19:13

    I think a nice way would be to make your back end return a error message when there are no records to display. You could use .catch after your axios.get().then() function to see if there are any errors returned by back end and then display it to the user.

    Look: What is the proper REST response code for a valid request but an empty data?

    0 讨论(0)
  • 2021-01-16 19:21

    You can make use of conditional rendering!

    render(){
    const filteredItems = this.getDataItems(this.state.filtered);
    const dataItems = this.getDataItems(this.state.data);
    
    if(dataItems){
    return(
     <div>Your Message</div>
    )
    }
    else{
    //Your normal code
    
    }
    }
    
    0 讨论(0)
  • 2021-01-16 19:30

    You can check when you get the data back and set an error if no data:

      getData(){
        const {Item,skip}=this.state;
        axios.get(`http://localhost:8001/parties?filter[limit]=${Item}&&filter[skip]=${skip}`)
        .then(response=>{
          console.log(response.data);
          if (!response.data.length) {
            this.setState({noData: true}) 
          } else {
            this.setState({
              data:response.data, noData: false
            })
          }
        })
      }
    

    Then in your render function:

    render() {
      if (this.state.noData) {
        return <p>No Data was returned!</p>;
      }
      ...
    
    0 讨论(0)
  • 2021-01-16 19:34

    You could check for the data before render the component and return another component if you don't have any. Using expressions such This example ‘’’ { doIHaveData ? < Component1 /> : < Component2 />} ‘’’

    Where Component1 has your functionality and Component2 return a message or a spinner loader whatever you want .

    I hope it helps!

    When you are checking for the empty array you could check for array type and length. I would personally do something like

     {Array.isArray(array) && array.length === 0 ? <component1/> : <component2/>} 
    
    0 讨论(0)
提交回复
热议问题