我正在学习 React,现在,我正在尝试向我的按钮添加一个 onClick 事件,单击该事件时,它将显示一个从 Rest API 获取的笑话。我阅读了文档,它说要发生 onclick 事件,您需要调用您使用的函数,在这种情况下是 componentDidMount。我最初使用{this.componentDidMount}并收到以下错误消息:Cannot read property 'setState' of undefined. 所以我做了一些研究,发现我需要使用箭头函数来调用 componentDidMount。我应用了它,当我单击按钮时,笑话没有改变,当我检查控制台时,没有任何错误。有人能说出可能出了什么问题以及如何解决吗?
import React, { Component } from 'react';
class DadJokesApi extends Component {
constructor(props){
super(props);
this.state = {
jokes: [],
};
}
componentDidMount(){
fetch('https://cors-anywhere.herokuapp.com/https://icanhazdadjoke.com/', {
headers: {
'Content-Type': 'appliction/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => this.setState(prev => ({jokes: prev.jokes.concat(data)})))
}
render () {
return (
<ul>
{this.state.jokes.map(joke =>
<div key={joke.id}>
<p>{joke.joke}</p>
<button onClick={()=>this.componentDidMount}></button>
</div>
)}
</ul>
)
}
}
export default DadJokesApi;
幕布斯6054654
相关分类