[英]React component rendering multiple times
我玩了一下 React,但我遇到了一个我无法弄清楚的棘手问题。
我有一个笑话组件,它基本上应该向https://sv443.net/jokeapi/v2
发出请求并显示结果。 发出请求并更新我的 state 都在一个方法中完成,然后在 componentDidMount() 方法中调用该方法。
这工作得很好,但我想让组件在点击时向 API 发出更多请求,所以我尝试做的是设置组件的 onClick 值等于使 Z6253F585155C17C2EE424234CE1 的方法。
我的问题是这样做会使我的页面向 api 发送带有请求的垃圾邮件,因此每次单击都会请求各种笑话,而我只想每次单击一个笑话。
代码就在下面:
class Joke extends React.Component {
constructor(props) {
super(props);
this.state = {
joke: '',
hover: false
};
this.getJoke = this.getJoke.bind(this);
}
//GET request for the joke
getJoke = () => {
let that = this;
// this.setState({ joke: '' });
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.response);
that.setState({ joke: this.response })
}
}
xhr.open('GET', 'https://sv443.net/jokeapi/v2/joke/Programming,Miscellaneous?blacklistFlags=nsfw,racist,sexist&format=txt');
xhr.send();
}
componentDidMount() {
this.getJoke();
}
render() {
let jokeClass = 'text' + (this.state.hover ? '' : ' shy');
console.log(jokeClass);
console.log(this.state.joke);
return (
<div id='joke' className={jokeClass} onMouseEnter={() => this.setState({ hover: true })} onMouseLeave={() => this.setState({ hover: false })} onClick={this.getJoke()}>
<p id='qualityContent'>
{!this.state.hover && 'Hover over me for a joke.\nClick me for another one.'}
{this.state.joke.length > 0 && this.state.hover && this.state.joke}
{this.state.joke.length === 0 && this.state.hover && 'Joke incoming'}
</p>
</div>
);
}
}
我非常感谢你们能给我的任何见解:)
使用onClick={() => this.getJoke()}
或onClick={this.getJoke}
。 当前,当调用渲染时,您正在运行此 function,其结果将分配给 onClick。
编辑:
应在<div>
元素上使用上述版本之一,而不是onClick={this.getJoke()}
。
原因是通过设置onClick={this.getJoke()}
你告诉 React on render 调用你的getJoke
方法并将它的结果分配为运行时的onClick
处理程序。 现在,因为getJoke()
正在发出请求并设置 state 值,所以会发生以下情况:
this.getJoke()
that.setState({ joke: this.response })
上设置结果onClick={this.getJoke()}
所以你的方法会被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.