我在console.log('check')
中做了componentDidMount()
,并且它在控制台中也有效。因此,我认为fetch()
我想念什么?
class App extends Component {
constructor(){
super()
this.state = {
robots: [],
searchfield: ''
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=> response.json())
.then(users =>this.setState({ robot: users}));
}
render(){
const filteredRobots = this.state.robots.filter(robots =>{
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
if (this.state.robots.length ===0){
return <h1>Loading</h1>//loading screen
} else {
return(
<div className='tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange} />
<CardList robots={filteredRobots}/>
</div>
);
}
}
}
export default App;
谢谢
答案 0 :(得分:-1)
在您的状态下,您正在将状态初始化为机器人,而不是像这样的机器人:
constructor(){
super()
this.state = {
robots: [], <- here
searchfield: ''
}
然后在setState中,您正在使用机器人,如下所示:
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=> response.json())
.then(users =>this.setState({ robot: users})); <- here
只需将其更改为robots: users
只是一个小错字...
当然,您可以将其清理一点,然后执行以下操作:
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=> response.json())
.then(robots =>this.setState({ robots}));
那也可以