如何使用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;
答案 0 :(得分:0)
当你的x或first为null
时会发生这种情况 return function(x){
if(x && x.first != null){
return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
}else
return x;
}
也不需要使用引号&#34;&#34;绑定时
value={product}
答案 1 :(得分:0)
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
应为x.title
答案 2 :(得分:0)
<ul>
{
this.state.map((item,key)=>
<li key={item.title}>
{item.title}
</li>
)}
</ul>
试试这个,让我知道 请告诉我你的阵列,看看它的结构如何