0

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

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

子组件开始渲染使用

componentDidMount()
{
   this.callservice(serverapi)
}

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

4

2 回答 2

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

于 2019-03-08T15:25:53.190 回答
0

您可以有一个名为 的全局变量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 中重新渲染真的很常见!

于 2019-03-08T17:22:04.723 回答