代碼解析React中setState同步和異步問題
React起源于Facebook的內(nèi)部項目。React的出現(xiàn)是革命性的創(chuàng)新,React的是一個顛覆式的前端框架。在React官方這樣介紹的它:一個聲明式、高效、靈活的、創(chuàng)建用戶界面的JavaScript庫,即使React的主要作用是構(gòu)建UI,但是項目的逐漸成長已經(jīng)使得react成為前后端通吃的WebApp解決方案。
angular中用的是watcher對象,vue是觀察者模式,react就是state了,他們各有各的特點,沒有好壞之分,只有需求不同而選擇不同。
React的官方網(wǎng)址:https://reactjs.org/GitHub
地址為:https://github.com/facebook/react
1.在React中,由React控制的事件處理函數(shù),如onClick, onChange等,setState是異步的
import React, { Component } from 'react';
export default class Input extends Component {
constructor(props) {
super(props);
this.state={
name: 'hello'
}
}
_onChange(e) {
this.setState({
name:' world'
})
console.log(this.state.name); //hello
}
render () {
return (
<div className='cp'>
<input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/>
</div>
);
}
}
2.在原生JS監(jiān)聽的事件中,如addEventListener, setState是同步的
import React, { Component } from 'react';
export default class Input extends Component {
constructor(props) {
super(props);
this.state={
name: 'hello'
}
}
_onChange(e) {
// do something
}
componentDidMount() {
let input = document.querySelector('.cp-input');
input.addEventListener('click', ()=>{
this.setState({
name:' world'
})
console.log(this.state.name); //world
})
}
render () {
return (
<div className='cp'>
<input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/>
</div>
);
}
}
3.在setTimeout中,setStatet是同步的
import React, { Component } from 'react';
export default class Input extends Component {
constructor(props) {
super(props);
this.state={
name: 'hello'
}
}
_onChange(e) {
// do something
}
componentDidMount() {
setTimeout(()=>{
this.setState({
name:' world'
})
console.log(this.state.name); //world
}, 1000)
}
render () {
return (
<div className='cp'>
<input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/>
</div>
);
}
}
以上就是解析React中setState同步和異步代碼詳解的詳細(xì)內(nèi)容,更多關(guān)于React setState同步和異步的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決react中l(wèi)abel標(biāo)簽for報錯問題
這篇文章主要介紹了react中l(wèi)abel標(biāo)簽for報錯問題,解決辦法就是react中l(wèi)abel標(biāo)簽沒有for屬性,用htmlFor代替for屬性,感興趣的朋友跟隨小編一起看看吧2022-02-02
使用reactjs優(yōu)化了進(jìn)度條頁面性能提高70%
這篇文章主要介紹了使用reactjs優(yōu)化了進(jìn)度條后頁面性能提高了70%的操作技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04

