【问题标题】:Is it possible to control a child component in react if the parent component render many times?如果父组件多次渲染,是否可以控制子组件进行反应?
【发布时间】:2019-03-08 15:00:21
【问题描述】:

我正在处理有关父组件渲染两次而子组件也渲染两次的问题。父级的现有代码是

<childform
  value ="name"
  serverapi={this.valueservice.api}
  update={this.update}
/>

子组件使用

开始渲染
componentDidMount()
{
   this.callservice(serverapi)
}

由于它的 componentDidMount 函数调用了两次,API 也渲染了两次,这必须避免,每次父渲染子的状态都会被刷新,所以我无法与状态进行比较,是否有可能检查或解决这个问题我可以参考的问题?这解决了我调用父级它调用 API 一次的次数

【问题讨论】:

  • 如果组件没有再次挂载,componentDidMount 只会运行一次。请检查导致 API 多次调用的上层组件
  • 是的,我有现有的场景代码,它是由另一个开发人员开发的,会出现不必要的渲染。由于父级调用了两次子级,因此子级 API 也调用了两次

标签: reactjs redux-form react-props react-state


【解决方案1】:

您传递给childform 的更新道具似乎是一个布尔值,指示组件是否应该重新渲染。如果是这种情况,您可以使用 shouldComponentUpdate() 生命周期方法来检查是否有更新并仅在为 true 时重新渲染:

shouldComponentUpdate(nextProps, nextState) {
  //You can perform more logic here such as 
  //return this.props.update === nextProps.update
  return nextProps.update;
}

您可以在这里找到更多信息:

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

【讨论】:

    【解决方案2】:

    您可以拥有一个名为 cache 的全局变量。

    这个缓存的作用是检查 your_awesome_api 之前是否被调用过。

    下面这段代码是常用的方法:

    // cache.js
    let cache = {};
    
    export default cache;
    
    // someComponent.js
    import cache from './cache';
    
    // ...ignore some react component code...
    
    componentDidMount() {
      if (cache['your_awesome_api']) {
        doSomething(cache['your_awesome_api'])
      } else {
        this.callservice(your_awesome_api).then(result => {
          cache['your_awesome_api'] = result
        })
      }
    }
    
    
    

    这样,您再也不用担心重新渲染问题了!

    react 中重新渲染真的很常见!

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2020-10-15
      • 2021-08-11
      • 2016-12-02
      • 2022-01-08
      • 2023-01-20
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多