[英]Why doesn't this code run, and instead sends me this error:(Unhandled Rejection (TypeError): this.state is not a function)
I am a beginner a was trying to code a react app as an exercise我是初学者,我正在尝试编写 React 应用程序作为练习
i am expecting to see some thing like this : https://github.com/aneagoie/robofriends but it give me this error Unhandled Rejection (TypeError): this.state is not a function (anonymous function)
我期待看到这样的事情: https : //github.com/aneagoie/robofriends但它给了我这个错误
Unhandled Rejection (TypeError): this.state is not a function (anonymous function)
import React, {Component} from 'react';
import SearchBox from './SearchBox';
import CardList from './CardList';
import './App.css'
import { robot } from './robot';
class App extends Component {
constructor(){
super()
this.state = {
robot: [],
searchField: ''
}
}
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {this.state({robot:robot})})
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value})
}
render(){
const filteredrobots = this.state.robot.filter(
robot =>{
return robot.name.includes(this.state.searchfeild)})
return(<div className ='tc'>
<h1>robot friends</h1>
<SearchBox searchChange = {this.onSearchChange}/>
<CardList robot = {filteredrobots}/></div>)
}
}
export default App;
dont understand what is going wrong thanks in advance不明白出了什么问题提前谢谢
It seems like the issue is in the function of componentDidMount
.问题似乎出在
componentDidMount
的功能上。
You tried setting the in that function but instead of doing this.setState, you did this.state.您尝试在该函数中设置 the,但您没有执行 this.setState,而是执行了 this.state。
This is how it should be:应该是这样:
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {this.setState({robot:robot})})
}
Also, when you try setting the state, it here in that componentDidMount function, I don't see anywhere that robot
is defined.... So the value of robot will be undefined.此外,当您尝试设置状态时,它在那个 componentDidMount 函数中,我看不到任何地方定义了
robot
......所以机器人的值将是未定义的。
Let me know if you need clarification.如果您需要澄清,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.