reactjs - React:当类的状态改变时防止自动刷新
问题描述
我是新来的反应。
我有一个基于类的组件。假设里面的代码是:
state = {message: "Hello"}
render(){
<div>
<p>this.state.message</p>
<button onclick={() =>this.setState({message: "World"})}>click here</button>
</div>
}
当我单击按钮时,屏幕上的显示从“Hello”变为“World”,但随后页面刷新,显示又回到默认的“Hello”。
我应该如何防止自动刷新?我希望我的页面在按下按钮后显示“世界”。
我真的很感谢你的帮助。
解决方案
元素的<button>
默认行为是提交页面(或它所在的表单),这会触发刷新。
为避免这种情况,请将其类型设置为button
:
<button type="button" onclick={() =>this.setState({message: "World"})}>click here</button>
推荐阅读
- javascript - 循环遍历数组对象以获取和显示值
- sql - 使用存储过程的最后一行中的单个值插入新行
- sqlite - 有什么好的方法可以将字节码直接传递给 sqlite3 吗?
- python - 从 pandas 函数创建数据框
- amazon-web-services - AWS EC2 实例 - 连接超时但 SG 存在
- javascript - JS - scrollTop 在移动设备和 Firefox 中不起作用
- php - 在 PHP 中按元素的 parent_id 合并数组
- tensorflow - 如何在 tensorflow 项目中可视化数据流
- python - 给定输入大小为 2 个单词,三元组预测下一个单词的行为应该是什么?
- r - 如何在循环中按字符名访问列表中的列表?