显示错误消息,即使有数据,有时也没有数据

时间:2020-10-20 15:11:11

标签: javascript reactjs

因此在React中,我有一个简单的搜索。它将数据显示在数组中。当搜索不匹配时,我会显示一条消息,提示“无结果...”。

该错误消息显示何时显示数据,尽管什么也没显示,但有时不显示。

enter image description here enter image description here

...

class Search extends Component {
  state = {
    orgNames: [],
    searchResult: [],
    errorMessage: null,
  };

  ....

  searchHandler = (e) => {
    const searchValue = e.target.value.toLowerCase();
    if (!searchValue) {
      this.setState({
        searchResult: [],
      });
    } else {
      const result = this.state.orgNames.filter((orgName) => {
        return orgName.toLowerCase().includes(searchValue);
      });
      this.setState({
        searchResult: result,
      });
    }

    if (searchValue.length >= 0 && this.state.searchResult.length === 0) {
      this.setState({
        errorMessage: "No Results...",
      });
    } else {
      this.setState({
        errorMessage: null,
      });
    }
  };

  ...
        {this.state.searchResult.map((res, key) => {
          return (
            <Link key={key} to={"/r/" + res}>
              <li>{res || <Skeleton />} </li>
            </Link>
          );
        })}
        {this.state.errorMessage === null ? (
          ""
        ) : (
          <li>{this.state.errorMessage}</li>
 ...

3 个答案:

答案 0 :(得分:3)

截至本文的分析为止,您必须在setState回调函数中进行条件检查。由于setState是异步函数。

    searchHandler = (e) => {
    const searchValue = e.target.value.toLowerCase();
    if (!searchValue) {
        this.setState({
            searchResult: [],
        });
    } else {
        const result = this.state.orgNames.filter((orgName) => {
            return orgName.toLowerCase().includes(searchValue);
        });
        this.setState({
            searchResult: result,
        },()=>{  console.log("search REa", this.state.searchResult)
            if ( this.state.searchResult.length === 0) {
                this.setState({
                    errorMessage: "No Results...",
                });
            } else {
                this.setState({
                    errorMessage: null,
                });
            }});
    }


};

我稍微更改了您的代码,请确认。

答案 1 :(得分:1)

编辑:

输入内容不显示错误消息时,不显示错误消息,而仅在输入结果不匹配时显示错误消息了吗?

我看不到您的数据,但我无法给出确切的信息,但也许像下面这样?

 if (searchValue !== searchResult || this.state.searchResult.length === 0)

原始代码的问题在于您取决于第一个条件和第二个条件。

//This is already true before anything is in the input, and is also true when there is something in the input
 if (searchValue.length >= 0 && this.state.searchResult.length === 0) 

下面的示例将您的条件移到函数的更高位置,并检查输入的值是否存在于数组中。如果不是,或者如果searchResult返回null,则显示错误。

searchHandler = (e) => {
        const searchValue = e.target.value.toLowerCase();
        if (!searchValue) {
            this.setState({
                searchResult: [],
            });
        }
        //if orgName array does not include search value OR if searchResult length === 0 then display error message
        else if (!orgName.toLowerCase().includes(searchValue) || this.state.searchResult.length === 0) {
            this.setState({
                errorMessage: "No Results...",
            });
        } else {
            const result = this.state.orgNames.filter((orgName) => {
                return orgName.toLowerCase().includes(searchValue);
            });
            this.setState({
                searchResult: result,
            });
        }

答案 2 :(得分:1)

尝试一下对我有用的

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: '',
            orgNames: ['IBM', 'Google', 'Apple', 'AppleIBMGoogle'],
            searchResult: ['IBM', 'Google', 'Apple', 'AppleIBMGoogle'],
            errorMessage: null,
        };
    }

    searchHandler = (e) => {
        const searchValue = e.target.value;
        const result = this.state.orgNames.filter((orgName) => {
            return orgName.toLowerCase().includes(searchValue.toLowerCase())
        })

        if (searchValue.length > 0 && result.length === 0) {
            this.setState({
                errorMessage: "No Results...",
                searchText: searchValue,
                searchResult: result,
            })
        } else {
            this.setState({
                errorMessage: null,
                searchText: searchValue,
                searchResult: result,
            })
        }
    }


    render() {
        const result = this.state.searchResult.map((res, key) => (
                <div key={key}>
                    <li>{res}</li>
                </div>
            )
        )

        console.log(this.state)

        return (
            <div>
                {this.state.errorMessage ? <li>{this.state.errorMessage}</li> : result}
                <input type="text" name='searchText' onChange={this.searchHandler} value={this.state.searchText} />
            </div>
        )

    }
}

export default App