如何使用http.get
从一个JSON调用中过滤数据?控制台说:
TypeError:无法读取未定义的属性'toLowerCase'
使用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或first为null时,应该会发生这种情况
return function(x){
if(x && x.first != null){
return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
}else
return x;
}
绑定时也不需要使用引号“”
value={product}
<ul>
{
this.state.map((item,key)=>
<li key={item.title}>
{item.title}
</li>
)}
</ul>
试试这个,让我知道,请告诉我你的阵列,看看它是如何结构化的
import React, { Component } from "react";
import { render } from "react-dom";
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
product: ""
};
this.SearchWord = this.SearchWord.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 (
<div className="App">
<input
type="text"
placeholder="SEARCH DATA"
onChange={this.SearchWord}
value={this.state.product}
/>
<ul>
{items.length &&
items.filter(x => x.title.toLowerCase().includes(product.toLowerCase()))
.map(item => <li key={item.title}>{item.title}</li>)
}
</ul>
</div>
);
}
}
render(<App />, document.getElementById("root"));
您的代码中几乎没有问题。
SearchWord
方法而不是componentWillMount
SearchWord
方法value={this.state.value}
x.first
which应该是x.title