我正在学习 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;
1 回答

幕布斯6054654
TA贡献1876条经验 获得超7个赞
没有得到预期结果的原因有几个:
componentDidMount
是一个生命周期函数。你不能使用它。的原因
Cannot read property 'setState' of undefined
是您不会将事件与this
in绑定constructor
我在您的代码中更新了几件事:
创建一个单独的函数,不使用生命周期函数作为点击事件
将函数与构造函数绑定
this
,使函数具有this
上下文。
在此处检查您的工作代码的 stackblitz 示例。
添加回答
举报
0/150
提交
取消