我是靠谱客的博主 背后睫毛膏,这篇文章主要介绍代码解析React中setState同步和异步问题,现在分享给大家,希望可以做个参考。

 React起源于Facebook的内部项目。React的出现是革命性的创新,React的是一个颠覆式的前端框架。在React官方这样介绍的它:一个声明式、高效、灵活的、创建用户界面的JavaScript库,即使React的主要作用是构建UI,但是项目的逐渐成长已经使得react成为前后端通吃的WebApp解决方案。

 angular中用的是watcher对象,vue是观察者模式,react就是state了,他们各有各的特点,没有好坏之分,只有需求不同而选择不同。

      React的官方网址:https://reactjs.org/GitHub

地址为:https://github.com/facebook/react

1.在React中,由React控制的事件处理函数,如onClick, onChange等,setState是异步的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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监听的事件中,如addEventListener, setState是同步的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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是同步的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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同步和异步代码详解的详细内容,更多关于React setState同步和异步的资料请关注靠谱客其它相关文章!

最后

以上就是背后睫毛膏最近收集整理的关于代码解析React中setState同步和异步问题的全部内容,更多相关代码解析React中setState同步和异步问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(154)

评论列表共有 0 条评论

立即
投稿
返回
顶部