本文介绍了React:如果没有记录,如何显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJS开发项目,我正在通过API从服务器获取数据.我进行了一些搜索过滤,如果没有可用的记录,我想显示消息吗?我是ReactJS的初学者,对ReactJS的了解不多.

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 am beginner to ReactJS and don't have much knowledge related to ReactJS.

代码:

        class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

推荐答案

您可以检查何时获取数据并在没有数据的情况下设置错误:

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>;
  }
  ...

这篇关于React:如果没有记录,如何显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 20:27