javascript - React 组件没有在 setState 上重新渲染
问题描述
我有以下代码。我正在使用 setState 方法 ( this.setState({ country: "", offset: "" });
) 设置状态,它不会导致render()
方法自行重新呈现。
state = { country: "", offset: "" };
onClicked = () => {
console.log("Fine Click away");
// Get the call back from props
let country = this.state.country;
let offset = this.state.offset;
this.setState({ country: "", offset: "" });
const callback = this.props.onpress;
if (callback) {
callback(country, offset);
}
};
getTheCountryName = event => {
this.setState({ country: event.target.value });
};
getTheOffSet = e => {
this.setState({ offset: e.target.value });
};
render() {
const Caption = this.props.caption;
return (
<div>
<br></br>
<br></br>
<div>Please enter the name of country and offset:</div>
<input
placeholder="Name of Country"
onChange={this.getTheCountryName}
/>
<input placeholder="offset" onChange={this.getTheOffSet} />
<br></br>
<br></br>
<button className="rectangular-button" onClick={this.onClicked}>
<div className="caption">{Caption}</div>
</button>
</div>
);
}
}```
解决方案
以任何方式重置状态都不会触发输入值的更新,因为您实际上并没有在要返回的 JSX 中使用您的状态。下面的代码会将值提供给输入,以便在您的状态更改时更新它们。你可以在这里阅读 React 中的表单和受控输入:
class App extends React.Component {
state = { country: "", offset: "" };
onClicked = () => {
console.log("Fine Click away");
// Get the call back from props
let country = this.state.country;
let offset = this.state.offset;
this.setState({ country: "", offset: "" });
const callback = this.props.onpress;
if (callback) {
callback(country, offset);
}
};
getTheCountryName = event => {
this.setState({ country: event.target.value });
};
getTheOffSet = e => {
this.setState({ offset: e.target.value });
};
render() {
const Caption = this.props.caption;
return (
<div>
<br></br>
<br></br>
<div>Please enter the name of country and offset:</div>
<input
placeholder="Name of Country"
onChange={this.getTheCountryName}
value={this.state.country}
/>
<input value={this.state.offset} placeholder="offset" onChange={this.getTheOffSet} />
<br></br>
<br></br>
<button className="rectangular-button" onClick={this.onClicked}>
<div className="caption">Reset</div>
</button>
</div>
);
}
}
推荐阅读
- cordova - 如何在 Framework7 中使用 AdMob Pro 插件?
- r - 如何在 SJplot 包中生成聚集标准错误?
- mysql - 基于另一个布尔列的列的总和值,分别为 true 和 false
- function - 数据框的列正在交换:当我按名称识别和分配列时,为什么我的循环会切换列值?
- node.js - 试图让我的输入值四舍五入到下两位小数
- python - 识别以口语介绍开头的 MP3 文件中钢琴音乐的开头,并使用 Python 删除口语部分
- spring-security - Spring Security,我们如何从数据库动态创建授权规则匹配器
- python - 从两个数组增加序列
- python - 从 python 脚本调用 matlab 总是显示 matlab 信息,即使没有显示标志
- javascript - 如何在一定时间 HTML / CSS 后淡入和淡出一个 div