首页 > 解决方案 > React:当类的状态改变时防止自动刷新

问题描述

我是新来的反应。

我有一个基于类的组件。假设里面的代码是:

state = {message: "Hello"}

render(){
<div>  
   <p>this.state.message</p>
   <button onclick={() =>this.setState({message: "World"})}>click here</button>
</div>
}

当我单击按钮时,屏幕上的显示从“Hello”变为“World”,但随后页面刷新,显示又回到默认的“Hello”。

我应该如何防止自动刷新?我希望我的页面在按下按钮后显示“世界”。

我真的很感谢你的帮助。

标签: reactjs

解决方案


元素的<button>默认行为是提交页面(或它所在的表单),这会触发刷新。

为避免这种情况,请将其类型设置为button

<button type="button" onclick={() =>this.setState({message: "World"})}>click here</button>

推荐阅读