猿问

在我添加箭头函数来调用我正在使用的函数后,onClick 事件不起作用

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


GCT1015
浏览 175回答 1
1回答

幕布斯6054654

没有得到预期结果的原因有几个:componentDidMount是一个生命周期函数。你不能使用它。的原因Cannot read property 'setState' of undefined是您不会将事件与thisin绑定constructor我在您的代码中更新了几件事:创建一个单独的函数,不使用生命周期函数作为点击事件将函数与构造函数绑定this,使函数具有this上下文。在此处检查您的工作代码的 stackblitz 示例。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答