【问题标题】:How to show an error message when no data is found while filtering过滤时找不到数据时如何显示错误消息
【发布时间】:2020-11-10 11:00:14
【问题描述】:

我有一个组件,我在其中进行搜索过滤和下拉过滤,过滤正在工作,但如果过滤时没有找到数据,我无法弄清楚在哪里显示错误。谁能帮我解决这个问题

 searchSpace = (event) => {
            this.setState({
              search: event.target.value,
            });
          };
    
 sortOptions = [
    {value: "ALL", label: "All"},
    { value: "Iphone", label: "Iphone" },
    { value: "Samsung", label: "Samsung" },
  ];

  getSelectedItem = (items, selectedValue) => {
    return items.find((item) => item.value === selectedValue);
  };

  dropdown = (event) => {
        console.log("filter", event.selectedItem.value);
        this.setState({
          filter: event.selectedItem.value,
        });
      };

     render() {
           const { details} = this.state;
          const items = this.state.details
              .filter((data) => {
                if (this.state.search == null) return data;
                else if (data.includes(this.state.search)) {
                  return data;
                }                
              })
              const data = items
              .filter((data) => this.state.filter === "" || data === this.state.filter)
              .map((data) =>
                   <>
                  <ShareCard></ShareCard>
                </>    
            );
    return (
  <Search placeHolderText="Search" onChange={(e) => this.searchSpace(e)}/>

<Dropdown id="filtering items={this.sortOptions}
 onChange={(e) => this.dropdown(e)}
  selectedItem={this.getSelectedItem(
 this.sortOptions,
 this.state.filter
 )} />

    <div>{data}</div>
    )
    );

【问题讨论】:

  • 如果items 是一个空数组,您是否想知道在您的 JSX 中的何处显示一些错误消息?
  • 对,我不确定在哪里放置布尔值或其他东西,当项目为空数组时显示错误消息

标签: javascript reactjs typescript error-handling filtering


【解决方案1】:

如果items 为空,则显示错误的一个非常简单的用例是使用conditional rendering。如果items数组长度为真,即大于零,则渲染数据,否则渲染错误信息。

<div>
  {items.length ? data : "Error: There are no items!!"}
</div>

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2018-08-19
    • 1970-01-01
    • 2019-08-06
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多