Reactjs React类组件中的箭头sintax
我在想,为什么showMore方法只有在我使用箭头sintax时才有效,如果我不使用它,然后单击按钮,控制台显示错误:TypeError:无法读取未定义的属性“setState”,但在componentDidMount中首次调用没有箭头sintax的方法时才有效Reactjs React类组件中的箭头sintax,reactjs,methods,components,Reactjs,Methods,Components,我在想,为什么showMore方法只有在我使用箭头sintax时才有效,如果我不使用它,然后单击按钮,控制台显示错误:TypeError:无法读取未定义的属性“setState”,但在componentDidMount中首次调用没有箭头sintax的方法时才有效 import React, { Component } from 'react'; class Jokes extends Component{ state = { joke: []}; showMore = ()
import React, { Component } from 'react';
class Jokes extends Component{
state = { joke: []};
showMore = () =>{
fetch('https://official-joke-api.appspot.com/random_ten')
.then(response => response.json())
.then(json => this.setState({ joke: json }));
}
componentDidMount(){
this.showMore();
}
render(){
const JOKES = this.state.joke;
return(
<div>
{JOKES.map(JOKE =>{
return(
<p key={JOKE.id}>{ JOKE.setup}<em>{JOKE.punchline}</em></p>
)
})}
<button onClick={this.showMore}>Show more jokes</button>
</div>
)
}
}
export default Jokes;
您需要一个arrow函数,以便showMore的作用域正确地限定为React类,而不是click处理程序。使用箭头功能时,这是React组件,它将具有setState等。不使用箭头功能时,这将是选定的元素