【发布时间】: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