【问题标题】:Unhandled Rejection (TypeError): Cannot read property 'filter' of undefined未处理的拒绝(TypeError):无法读取未定义的属性“过滤器”
【发布时间】:2020-06-20 22:00:01
【问题描述】:

我正在尝试在 react.js 中过滤搜索我的 API 数据,但出现此错误,无法读取未定义的属性“过滤器”。这是我的 JSON 数据链接:https://alert-amigo-api.herokuapp.com/products/ 由于 JSON 数据返回一个对象数组,因此我在 props 中声明并使用了相同的对象。有什么问题?

    import FilterResults from 'react-filter-search';
    import React, { Component } from "react";
    class UserProfile extends Component {
    constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      products: [],
      value: ''
    };
  }
  componentWillMount() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            products: result.products
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
      console.log(this.state.products[0]);
  }
  handleChange = event => {
    const { value } = event.target;
    this.setState({ value });
  };
  render() {
    const { error, isLoaded, products, value } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
      } else {
    return (
      <div className="content-margin">
        <input type="text" value={value} onChange={this.handleChange} />
        <FilterResults
          value={value}
          products={products}
          renderResults={products => (
            <div>
              {products.map(el => (
                 <div>
                  <span>{el.productName}</span>
                 </div>
               ))}
             </div>
           )}
         />
       </div>
      );
    }
  }
}
export default UserProfile;

【问题讨论】:

  • 我在您的代码中没有看到对 .filter 的任何调用。请包括错误的堆栈和发生.filter 调用的代码。
  • @CherryDT import FilterResults from 'react-filter-search';
  • 不,我不是这个意思。它说Cannot read property 'filter' of undefined,但您的代码从不访问任何属性filter。同样,请同时包含完整的错误 stack
  • @Manisha 您要过滤的数组未定义,可能只是 console.log products
  • @CherryDT 图书馆在幕后工作。

标签: json reactjs api search filter


【解决方案1】:

通过测试该确切示例,您会注意到获取 URL 不返回产品:

fetch('https://jsonplaceholder.typicode.com/users')

网址应该是:

fetch('https://alert-amigo-api.herokuapp.com/products/')

现在result.products 确实包含一个数组。我建议稍微对您的代码进行防弹:

    (result) => {
      this.setState({
        isLoaded: true,
        products: result.products || [] // <-- add empty array
      });

或者,如果您愿意,在渲染方法上:

render() {

  { products &&
    <FilterResults ... />
  }

}

【讨论】:

猜你喜欢
  • 2019-04-07
  • 2019-07-19
  • 2019-06-03
  • 2020-04-09
  • 2019-11-13
  • 2021-10-19
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多