react 更新一个值后立刻使用该值(类似vue $nextClick)

案例需求:

案例描述:点击按钮,使count+1后,立马发起请求

解决问题得核心:就是依靠count更新后,会触发componentDidUpdate生命周期函数,比对值得是否有变化,有变化,就触发网络请求。这部分知识点在react官网的componentDidUpdate

import React from 'react';
import {  View, Text } from 'react-native';

class CountScreen extends React.Component{
    constructor(props){
        super(props);
        this.state={
            count: 0
        }
    }
    //就是靠更新后,触发该生命周期函数,比对值得是否有变化
    componentDidUpdate(prevProps, prevState, snapshot){
        if(prevState.count != this.state.count){
            //发起网络请求
            alert("发起网络请求");
        }
    }
    increment=()=>{
        this.setState((state)=>{
            return {
                count: state.count+1
            }
        });
    }
    render(){
        return (
            <View>
                <Text onPress={this.increment}>点击按钮count+1</Text>
            </View>
        )
    }
}

componentDidMount触发次数太多导致的问题

事实上,这样的案例过于简单,业务复杂时,componentDidMount 会因为state的不断变化,多次进入componentDidMount函数内的判断条件里面(暂时没有想到好的案例,直接写解决方法)

思路 :在this.setState()时,添加标志为 true ,在进入componentDidUpdate里判断条件后,在将标志设置为false,这样就保证触发的精准性

...
this.state = {
            pullFlag: false, //上拉分页请求的标志
            isRefresh: false, //下拉刷新发起请求的标志
            reconnectFlag: false, //断网发起请求的标志
 };

 componentDidUpdate(prevProps, prevState, snapshot) {
        //上拉分页请求
        if (this.state.pullFlag && prevState.pageIndex != this.state.pageIndex) {
            // console.log("上拉继续分页请求数据");
            this.getIdeaData();
            this.setState({pullFlag: false});
        }

        //断网时,再次尝试连接
        if (this.state.reconnectFlag && prevState.pageIndex != this.state.pageIndex && this.state.pageIndex == 1 && this.state.ideaArr.length == 0) {
            // console.log("断网请求");
            this.getIdeaData();
            this.setState({reconnectFlag: false});
        }

        //下拉刷新(我怎么确定这是下拉刷新)
        
        if(this.state.isRefresh && this.state.pageIndex == 1 && this.state.ideaArr.length == 0){
            // console.log("下拉刷新触发");
            this.getIdeaData();
            this.setState({isRefresh:false});
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tengyuxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值