我正在尝试在react.js中过滤搜索我的API数据,但出现此错误,无法读取未定义的属性'filter'。这是我的JSON数据链接:https://alert-amigo-api.herokuapp.com/products/由于JSON数据返回一个对象数组,因此我在道具中声明了该对象并使用了它们。有什么问题吗?
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;
通过测试该确切示例,您会发现获取URL不会返回产品:
fetch('https://jsonplaceholder.typicode.com/users')
URL应该是:
fetch('https://alert-amigo-api.herokuapp.com/products/')
现在result.products
确实包含一个数组。我建议对您的代码进行稍微的防弹:
(result) => { this.setState({ isLoaded: true, products: result.products || [] // <-- add empty array });
或者,如果您愿意,可以使用render方法:
render() {
{ products &&
<FilterResults ... />
}
}