zoukankan      html  css  js  c++  java
  • react爬坑---通过请求接口,返回条件判断渲染组件AB

    在react组件开发中,遇到需要请求接口来判断展示组件A或者B,但由于react生命周期函数,组件第一次render的时候,接口还没有返回数据,无法确定render什么组件。此时,新增一个布尔值状态isResOk: false,如果isResOk为false,请求没有成功,则不展示任何组件;如果isResOk为true,请求成功,再根据接口返回值判断展示哪一个组件。

    在render函数里面,通过条件1进行判断接口是否返回:

    (1)接口没有返回,那么return false,不渲染任何组件;

    (2)接口有返回,通过条件2判断展示哪个组件。

     1 class A extends Component {
     2   static propTypes = {
     3     children: PropTypes.any,
     4     isShowInfo: PropTypes.func,
     5   }
     6   state = {
     7     isShow: true,
     8     isResOk: false,
     9   }
    10 
    11   componentDidMount() {
    12     const { isShowInfo } = this.props
    13     isShowInfo().then(res => {
    14       this.setState({
    15         isShow: res.Displayed,
    16         isResOk: true,
    17       })
    18     })
    19   }
    20 
    21   renderTitleNotic = () => {
    22     return (
    23       <strong>提醒:</strong>
    24     )
    25   }
    26 
    27   render() {
    28     const { children } = this.props
    29     const { isShow, isResOk } = this.state
    30     if (isResOk) {
    31       return isShow ? children : this.renderTitleNotic()
    32     } else {
    33       return false
    34     }
    35   }
    36 }
    37 export default A

    备注:

    尝试过,如果请求接口还未返回数据时,调用Loading组件,会存在第一次render为Loading组件,请求接口返回数据,更新数据后render为A||B组件 ;会导致Loading组件卸载的时候,在更新数据,造成内存泄漏问题。

  • 相关阅读:
    [CF340D]Bubble Sort Graph/[JZOJ3485]独立集
    [JZOJ3484]密码
    [HDU1756]Cupid's Arrow
    Luogu P4006 小 Y 和二叉树
    Luogu P4040 [AHOI2014/JSOI2014]宅男计划
    Luogu P3243 [HNOI2015]菜肴制作
    Luogu P3942 将军令
    Luogu P4823 [TJOI2013]拯救小矮人
    Luogu P3620 [APIO/CTSC 2007]数据备份
    BZOJ3709 [PA2014]Bohater
  • 原文地址:https://www.cnblogs.com/minyDong/p/13311235.html
Copyright © 2011-2022 走看看