【问题标题】:TypeError: item.name.toLowerCase(...).include is not a function reactjsTypeError: item.name.toLowerCase(...).include 不是函数 reactjs
【发布时间】:2019-06-11 10:19:07
【问题描述】:

你好,我是这个 reactjs 的新手,我目前在 Egghead 尝试一些课程,当我尝试这个 topic 关于使用映射从数据数组创建 React 组件时 我得到了一些错误,我不明白,因为我已经有相同的代码

import React from 'react'

class  Filter extends React.Component{
constructor(){
    super()
    this.state = {
        items : [],
        filter :""
    }
}

componentWillMount(){
    fetch('https://swapi.co/api/people/?format=json')
    .then(response => response.json())
    .then(({results: items})=>
          this.setState({items})  
    )
}

filter(event){
    this.setState({filter: event.target.value})
}

render(){
    let items = this.state.items
    console.log(items)
    if(this.state.filter){
        items = items.filter( item => 
        item.name.toLowerCase()
        .include(this.state.filter.toLowerCase()))
    }

    return(
        <div>
            {this.state.filter}
            <input type="text" onChange={this.filter.bind(this)}/>
            {items.map(item => <Org key={item.name} org={item}/>)}
        </div>
    )

}

    }
    const Org = (props) => <h4 >{props.org.name}</h4>

    export default Filter

这个error当我尝试过滤它时显示,就像我不能用键名调用数组项,该数组来自api

【问题讨论】:

  • 这是includes,而不是include

标签: reactjs


【解决方案1】:

您要查找的函数是includes。你打错字了

item.name.toLowerCase().includes(this.state.filter.toLowerCase()))

【讨论】:

    【解决方案2】:

    您可以添加检查项目是否为string 类型以防万一。

    类似:

    if (item &amp;&amp; typeof item === "string") item.name.toLowerCase();

    因为您的数组中总是有可能填充string 类型以外的元素。

    【讨论】:

    • 结合@Treycos 所说的。
    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2022-07-27
    • 2019-08-05
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多