您好,欢迎来到叨叨游戏网。
搜索
您的当前位置:首页React 18 系统精讲(五)获取网络api && 使用setState异步开发

React 18 系统精讲(五)获取网络api && 使用setState异步开发

来源:叨叨游戏网

一:react 获取网络api  

(一)之前我们模拟数据是直接在组件开头引入json数据的方式

import robots from './mockdata/robots.json';

然后通过以下方式向子组件传值 :

robots.map(r => <Robot id={ r.id } name={ r.name } email={r.email }

(二)之后我们将通过获取网络api的方式,分为四步
1.专门存储模拟数据的网站  : https://jsonplaceholder.typicode.com

    此处使用的是:https://jsonplaceholder.typicode.com/users  
2.在接口数据state中定义新的数据robotGallery,并在构造函数中初始化robotGallery
3.在组件挂在到页面数据初始化完成时执行钩子函数:

componentDidMount() { 
    fetch ("https://jsonplaceholder.typicode.com/users")   //获取api假数据  此时获取到的数据是promise格式,需转化成json格式
    .then (response => response.json())   //将promise格式转换成json格式
    .then ((data) => this.setState( {robotGallery: data} )) //将data值赋值给robotGallery
  }

4.之后在render(){}函数中就可以使用this.state.robotGallery 来向子组件传值:

this.state.robotGallery.map(r => <Robot id={ r.id } name={ r.name } email={r.email } 

二:使用setState异步开发

setState()  是异步的还是同步的?

答:异步更新,同步执行。

setState() 本身并非异步,但对state的处理机制给人一种异步的假象。
state处理一般发生在生命周期变化的时候。

关于多次调用setState的更新问题如下:

setState的更新逻辑:

当前state的setState重复多次执行的时候,会对比该state的更新数据从而将多次的state整合成单次的state,相同的情况只执行一次,不同的情况则以最新的一次setState为主;

而对上一次preState进行更新的情况,因为每一次更新的state对象都不一样,所以可以多次执行。

下面的代码则只会执行this.state.count + 3

 this.setState({ count: this.state.count + 1 }, () => {
   console.log(this.state.count)
 });
 this.setState({ count: this.state.count + 2 }, () => {
   console.log(this.state.count)
 });
 this.setState({ count: this.state.count + 3 }, () => {
   console.log(this.state.count)
 })

下面的代码都会执行preState.count + 1;preState.count + 2;preState.count + 3

this.setState((preState,preProps) => {return {count: preState.count + 1}}, () => {
     console.log(this.state.count)
});
this.setState((preState,preProps) => {return {count: preState.count + 2}}, () => {
     console.log(this.state.count)
 });
this.setState((preState,preProps) => {return {count: preState.count + 3}}, () => {
     console.log(this.state.count)
})
注:setState() 的两个参数,第1个参数可以是js表达式,也可以是函数;第2个参数是回调函数

 详情可参考:

react的setState到底是同步还是异步? - monkeySoft - 博客园 (cnblogs.com)

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务