React之this.setState方法
2023-09-11 14:19:18 时间
需要注意的是
this.setState
方法,他是一个异步的方法
例子
代码
import {Component, createRef} from 'react'
export default class NameForm extends Component {
inpEle = createRef()
state = {
value: ""
}
handleClick = () => {
const value = this.inpEle.current.value;
console.log("value",value);
this.setState({ value:value });
console.log("this.state",this.state);
console.log(`提交的数据为${this.state.value}`);
}
render() {
return (
<>
<input type="text" ref={this.inpEle}/>
<button onClick={this.handleClick}>提交</button>
</>
);
}
}
效果
- 当我们首次输入值进行点击的时候,你会发现,我们已经拿到了value的值,并执行
this.setState
,把它放到了state
中 - 但是我们打印出来的state中的value,仍旧是一个空的字符串,也就是我们不能立即拿到
setState
设置的值
知识点
通过上面的效果我们就会发现,其实
this.setState
他是一个异步的方法,官网
- 只有在同步代码执行完的某一个时刻,
this.state
相关的属性值才会改变 - 这个时候我们需要站在声明周期的角度去思考
this.setState
的执行
相关文章
- React系列——websocket群聊系统在react的实现
- Runtime 方法替换 和 动态添加实例方法 结合使用
- 使用JDBCTemplate实现与Spring结合,方法公用 ——Emp实现类(EmpDaoImpl)
- unity 改变鼠标样式的两种方法
- 用Python计算三角函数之acos()方法的使用
- [React] Use react styled system with styled components
- [React Testing] Test react-router-dom Router Provider with createMemoryHistory
- [React Testing] Test Drive Mocking react-router’s Redirect Component on a Form Submission
- [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
- [React] Override webpack config for create-react-app without ejection
- [React Intl] Render Content Based on a Number using react-intl FormattedMessage (plural)
- [React] Create an Auto Resizing Virtualized List with react-virtualized
- [React Testing] Test your Custom Hook Module with react-hooks-testing-library
- [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
- [React Intl] Format a Date Relative to the Current Date Using react-intl FormattedRelative
- SAP CRM IBASE的archive方法
- 多重共线性问题的几种解决方法
- atitit.React 优缺点 相比angular react是最靠谱的web ui组件化方案了
- 从零开始学_JavaScript_系列(22)——dojo(9)(表单、JsonRest的post方法,widget的使用思路)
- 内核不中断前提下,Gaussdb(DWS)内存报错排查方法
- js几个易混淆方法速学
- shell中逻辑与的两种表示方法
- MATLAB-蒙特卡罗方法
- Ubuntu 安装package提示依赖: XXX 但是它将不会被安装 解决方法
- 【taro react hooks 错误解决】---- Warning: Can‘t perform a React state update on an unmounted component.
- 在 Linux 中强制卸载的 3 种方法显示“设备正忙”
- 3D地形多层纹理混合加阴影渲染方法