網(wǎng)站首頁 編程語言 正文
我們編寫這樣一段代碼
import React from "react"
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
cont: 0
}
}
componentDidMount() {
this.setState({
cont: this.state.cont+1
})
}
render(){
return (
<div>
{ this.state.cont }
</div>
)
}
}
我們在state中定義了一個(gè)cont 值是 0 然后 在componentDidMount 頁面第一次渲染完成后執(zhí)行的生命周期中 給他加一 然后我們運(yùn)行代碼
沒錯(cuò) 一開始是0 頁面第一次掛載完成 加一 變成了 1 是沒問題的 然后我們將componentDidMount的代碼改成這樣
給他多加幾次
但是 運(yùn)行之后 我們會(huì)驚奇的發(fā)現(xiàn) 還是1
因?yàn)?setState 這個(gè)函數(shù)是個(gè)異步執(zhí)行的 所以 相當(dāng)于 他們接到的this.state.cont都是0 那0加一 自然就是 1了
所以 相當(dāng)于 三次都給出了同樣的值
那么 想解決這個(gè)問題 我們可以這樣寫
import React from "react"
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
cont: 0
}
}
componentDidMount() {
console.log("componentDidMount");
this.setState((proState,props) => ({
cont: proState.cont+1,
}))
this.setState((proState,props) => ({
cont: proState.cont+1
}))
this.setState((proState,props) => ({
cont: proState.cont+1
}))
}
render(){
return (
<div>
{ this.state.cont }
</div>
)
}
}
setState直接去那上一次的值 做操作
最后 得到了 6 因?yàn)?componentDidMount 執(zhí)行了兩次 不過 至少驗(yàn)證了 我們這個(gè)方法解決了異步連續(xù)調(diào)用的問題
然后 就是另一個(gè)問題 我們 componentDidMount 的代碼改成這樣
componentDidMount() {
this.setState({
cont: this.state.cont+1
})
console.log(this.state.cont);
}
就還是那個(gè)問題 因?yàn)?setState是異步的 所以 你在這之后打印 肯定也拿不到最新的值
我們改成這樣
componentDidMount() {
this.setState({
cont: this.state.cont+1
}, () => {
console.log(this.state.cont);
})
}
setState其實(shí)提供了一個(gè) 修改完成后的回調(diào)
我們再回到中輸出即可
原文鏈接:https://blog.csdn.net/weixin_45966674/article/details/131462205
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2022-09-24 C#/VB.NET實(shí)現(xiàn)PPT或PPTX轉(zhuǎn)換為圖像功能_C#教程
- 2022-04-01 使用Git clone代碼失敗的解決方法
- 2021-12-02 C/C++?Qt數(shù)據(jù)庫SqlRelationalTable關(guān)聯(lián)表詳解_C 語言
- 2022-07-07 Python推導(dǎo)式使用詳情_python
- 2022-04-28 shell?腳本中獲取命令的輸出的實(shí)現(xiàn)示例_linux shell
- 2022-02-22 Uncaught RangeError: Maximum call stack size excee
- 2022-04-09 在Mybatis中使用自定義緩存ehcache
- 2022-08-04 如何利用python實(shí)現(xiàn)列表嵌套字典取值_python
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支