我正在运行此React应用并收到错误消息:- 'TypeError:无法读取未定义的属性'filter'
在这种情况下,构造函数被调用两次,并且this.state.cats等于[], 然后didComponentMount被调用两次,并且setState({cats:catsList})设置this.state.cats = undefined出于某种原因。 菜鸟在这里,我们会提供任何帮助。
import React, { Component } from 'react';
import CatsList from './CatsList';
import logo from './logo.png';
import SearchBox from './SearchBox';
export default class App extends Component {
constructor(){
super();
this.state = {
cats: [],
searchField:''
}
}
onCatNameSearch = (event) => {
this.setState({searchField : event.target.value})
}
render(){
const filterdCats = this.state.cats.filter(cat => cat.name.toLowerCase().includes(this.state.searchField.toLowerCase()));
return (
<div className="tc">
<img src={logo} className="w-20" alt="logo" />
<SearchBox searchChange={this.onCatNameSearch}/>
<CatsList cats={filterdCats} />
</div>);
}
//since it is part of react, no need for arrow functions
componentDidMount(){
fetch('https://mak947.github.io/kitties/cats.json')
.then(response =>{
response.json();
})
.then(catsList =>{
this.setState({cats: catsList});
})
}
}
答案 0 :(得分:0)
您做的诺言链错误,如果要添加另一个.then
,则需要返回值,因此需要返回response.json()
componentDidMount(){
fetch('https://mak947.github.io/kitties/cats.json')
.then(response =>{
return response.json();
})
.then(catsList =>{
this.setState({cats: catsList});
})
}