如何使用 http.get
过滤来自一个 JSON 调用的数据?
控制台说:
TypeError: Cannot read property 'toLowerCase' of undefined
使用 Angular 可以轻松完成一次管道服务并完成,但使用 ReactJS 很多事情都很复杂。
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function searchingData(product) {
return function(x){
return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
}
}
class App extends Component {
constructor(props){
super(props);
this.state = {
items : [],
product: ''
};
this.componentWillMount = this.componentWillMount.bind(this);
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then( data => this.setState({ items : data }) );
}
SearchWord(event) {
this.setState({
product: event.target.value
})
}
render() {
const {items, product} = this.state;
return (
<Router>
<div className="App">
{/* SHOW JSON */}
<input type="text" placeholder="SEARCH DATA" onChange={this.componentWillMount} value="{product}" />
<ul>
{
items.filter(searchingData(product)).map(item =>
<li key={item.title}>
{item.title}
</li>
)}
</ul>
</div>
</Router>
);
}
}
export default App;
最佳答案
当您的 x 或第一个为 null 时,应该会发生这种情况
return function(x){
if(x && x.first != null){
return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
}else
return x;
}
绑定(bind)时也不需要使用引号“”
value={product}
关于javascript - 过滤器 JSON 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071564/