收到错误 this.setState 不是 class 组件中的函数
getting error this.setState is not a function in class component
我正在尝试学习 React js。当我在 React js 中调用我的第一个 api 时,出现错误 Unhandled Rejection (TypeError): this.setState is not a function。我厌倦了找出这个错误。请检查我的代码,让我知道我做错了什么。谢谢
import React from 'react';
class Post extends React.Component {
constructor(props){
super(props);
this.setState = {posts: []}
}
componentDidMount(){
this.getPost();
}
getPost(){
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(({data}) => this.setState({ posts: data }));
}
render(){
return (
<div>
<h2>Post</h2>
</div>
)
}
}
export default Post;
您的状态初始化有误。应该是 this.state
.
改变
constructor(props){
super(props);
this.setState = {posts: []}
}
至
constructor(props){
super(props);
this.state = {posts: []}
}
我正在尝试学习 React js。当我在 React js 中调用我的第一个 api 时,出现错误 Unhandled Rejection (TypeError): this.setState is not a function。我厌倦了找出这个错误。请检查我的代码,让我知道我做错了什么。谢谢
import React from 'react';
class Post extends React.Component {
constructor(props){
super(props);
this.setState = {posts: []}
}
componentDidMount(){
this.getPost();
}
getPost(){
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(({data}) => this.setState({ posts: data }));
}
render(){
return (
<div>
<h2>Post</h2>
</div>
)
}
}
export default Post;
您的状态初始化有误。应该是 this.state
.
改变
constructor(props){
super(props);
this.setState = {posts: []}
}
至
constructor(props){
super(props);
this.state = {posts: []}
}