如果 parent 组件渲染多次,是否可以控制 child 组件进行反应?
Is it possible to control a child component in react if the parent component render many times?
我正在处理有关 parent 组件渲染两次并且 child 组件也渲染两次的问题。 parent 的现有代码是
<childform
value ="name"
serverapi={this.valueservice.api}
update={this.update}
/>
child 组件开始渲染使用
componentDidMount()
{
this.callservice(serverapi)
}
因为它的 componentDidMount 函数调用了两次,所以 API 也渲染了两次,这是必须避免的,每次 parent 渲染 child 的状态都会被刷新,所以我无法与状态相比,是否可以检查或解决我可以参考的这个问题?这解决了多少次我调用 parent 它调用 API 一次
您传递给 childform
的更新道具似乎是一个布尔值,指示组件是否应该重新呈现。如果是这种情况,您可以使用 shouldComponentUpdate()
生命周期方法来检查是否有更新,并且仅在为真时才重新呈现:
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
您可以有一个名为 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 中重新渲染真的很常见!
我正在处理有关 parent 组件渲染两次并且 child 组件也渲染两次的问题。 parent 的现有代码是
<childform
value ="name"
serverapi={this.valueservice.api}
update={this.update}
/>
child 组件开始渲染使用
componentDidMount()
{
this.callservice(serverapi)
}
因为它的 componentDidMount 函数调用了两次,所以 API 也渲染了两次,这是必须避免的,每次 parent 渲染 child 的状态都会被刷新,所以我无法与状态相比,是否可以检查或解决我可以参考的这个问题?这解决了多少次我调用 parent 它调用 API 一次
您传递给 childform
的更新道具似乎是一个布尔值,指示组件是否应该重新呈现。如果是这种情况,您可以使用 shouldComponentUpdate()
生命周期方法来检查是否有更新,并且仅在为真时才重新呈现:
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
您可以有一个名为 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 中重新渲染真的很常见!