【问题标题】:ReactJs filtering results with .include() not working.include()的ReactJs过滤结果不起作用
【发布时间】:2020-10-27 22:00:28
【问题描述】:

我正在尝试使用.includes() 函数通过在输入字段中键入来过滤数据表的行,但它会引发以下错误:

TypeError:无法读取未定义的属性“包含”

// Create variable for json data
        const countries = this.state.fullData;

        // Map through API results and create an object
        let rows = countries.map((countries, index) => {

            return (
                {
                    key: index,
                    country: countries.Country_text,
                    confirmed: countries['Total Cases_text'],
                    new: countries['New Cases_text'],
                    deaths: countries['Total Deaths_text'],
                    recovered: countries['Total Recovered_text'],
                }
            )
    
        });

        const getCountry = (e) => {

            const filteredData = rows.filter(countries =>
                //countries.country.includes(this.state.value),
                console.log('Countries list:', countries.country)
            );

            this.setState({
                value: e.target.value,
                dataSource: filteredData
            });
        }

但是,如果我通过控制台退出 countries.country,我会看到预期的国家/地区列表。

Countries.js:92 Countries list: Portugal<br/>
Countries.js:92 Countries list: Bolivia<br/>
Countries.js:92 Countries list: Panama<br/>

...

谢谢

【问题讨论】:

  • 根据您的日志,countries.country一个 值,而不是列表。

标签: javascript reactjs api filter


【解决方案1】:

rows 是一个数组,通过在其上使用过滤器,您将遍历该数组中的每个元素,该数组是一个对象,所有属性都在 map 方法中分配给它。

我假设属性country 是一个字符串,并且由于includes() 是用于数组的方法,因此使用countries.country.includes() 将不起作用。

filter() 接受一个应该返回真或假的谓词,所以你要做的是

const filteredData = rows.filter(countries =&gt; countries.country === this.state.value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 2018-10-05
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多