javascript - 使用 onClick 无休止地重新渲染 React 组件
问题描述
我希望 result.js 中按钮的 onClick 事件呈现我的 Spinner 组件,并且到目前为止(有点)让它这样做。目前,Spinner 主要有一些 console.log() 语句,并且它一直在记录“Rendered spinner”。单击按钮后无休止,大约每秒一次。作为记录,返回的段落没有显示,但我还没有开始调试它。另外,我在 Result.js 中排除了一些我认为不相关的代码。
现在,我只想让 Spinner 在按下按钮后只渲染一次。有小费吗?
结果.js:
import React, { Component } from "react";
import { connect } from "react-redux";
import Spinner from "./spinner";
class UnboxResult extends Component {
constructor(props) {
super(props);
this.state = {
showSpinner: false
};
this.handleUnboxClicked = this.handleUnboxClicked.bind(this);
}
handleUnboxClicked(event) {
event.preventDefault();
console.log("Inside handleUnboxClicked");
this.setState({
showSpinner: true
});
}
render() {
return (
<section className="opening">
<div className="container">
<div className="row">
<button onClick={this.handleUnboxClicked}>UNBOX</button>
</div>
<div className="row">
{this.state.showSpinner ?
<Spinner items={this.props.unbox.items}/> :
null}
</div>
</div>
</section>
);
}
}
export default connect(state => ({
unbox: state.unbox
}))(UnboxResult);
微调器.js:
import React, { Component } from 'react';
class Spinner extends Component {
constructor(props) {
console.log("Before super");
super(props);
console.log("Ran constructor.");
}
render(){
console.log("Rendered spinner.");
return(
<p>Spinning..</p>
);
}
}
export default Spinner;
解决方案
您可以添加一个处理程序方法来更新微调器的状态
handleClick(){
this.setState({
showSpinner: true
})
}
在你的渲染中它需要作为道具传递
<div className="row">
{this.state.showSpinner ?
<Spinner handleClick={this.handleClick}/> :
null}
</div>
在您的微调器组件返回中,您可以使用 onclick 触发它
<button onClick = {this.props.handleClick} > Click </button>
这将允许您更新父项中的状态,您可能想弄清楚如何在微调器中一次显示一个项目,并且仅在没有项目可显示时将状态设置为 false。
对不起,如果我误解了你的评论。
推荐阅读
- python - 如何在不使用任何按钮的情况下更改条目值时更新标签值?
- python - 在 Python 中更改文件
- azure - 秘密和钥匙 - 活动中心
- reactjs - 使用 ExpressJS 和 webpack + redux + sass 的 SSR 功能
- python - np.where 还检查多维数组中的子元素
- elasticsearch - 我的弹性搜索请求有什么问题吗?
- sql - 提取具有复杂模式 SQL 的字符串的一部分
- python - 写入方法odoo中的Nonetype对象
- sql - 如何在 Postgresql 中获取特定案例的领先价值?
- vue.js - Nuxt 默认进度条在导航到没有 asyncData 或 fetch 的页面时变为红色