案例需求:

案例描述:点击按钮,使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});
        }
    }

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐