React:如果在obj中找不到数据,如何显示错误消息

时间:2019-03-15 20:36:19

标签: javascript reactjs ecmascript-6

我正在从事React项目,我是ReactJS的初学者。实际上,我已经实现了搜索过滤器的逻辑。在搜索是否找不到目标数据时,我想显示错误消息。我还将提供代码供参考,但我想讲一些逻辑要点。我创建了renderData数组,正在使用filter result更新它。如果用户正在键入并且在数组中未找到与查询相关的数据,我想做出一个逻辑,那么我想显示一个错误。请有人帮我解决这个问题。谢谢

代码

        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' ))

2 个答案:

答案 0 :(得分:1)

一个不错的选择是:

getData()方法中,如果数组为空,则可以在状态中设置错误。您可以使用underscore.js,lodash或

检查数组是否为空
if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

示例:https://codepen.io/anon/pen/qvoGZp

答案 1 :(得分:1)

随时随地将过滤后的数据保留在您的州或班级中。例如;

 constructor(props){
    super(props);
    this.state={
      includes: false,
    }
  }

     componentDidMount(){
           this.filtered = [];
       }

     searchHandler(event){
        if(event.target.value.toLowerCase().includes(YOUR_STRING_TO_CHECK.toLowerCase())
           { 
             this.filtered.push(event.target.value);
             this.setState({includes:true});
           }
        });
      }

   render()
     { 
        if(!this.state.includes)
        return(
        <div> ERROR</div> 
        )
        else
        return(<div> NOT ERROR </div>)
     }

尝试类似的方法。逻辑相同。如果您想保留过滤的数据,请将其保存在课堂上某个地方。

相关问题