[英]React - does a child component re-mount each time the parent component renders?
In this very basic example I am including the component Bar
inside the render function of component Foo
. 在这个非常基本的示例中,我将组件
Bar
包含在组件Foo
的render函数中。 I am observing that the componentDidMount
method for Bar
is firing each time Foo re-renders - is this the correct behaviour? 我观察到Foo每次重新渲染时,都会触发
Bar
的componentDidMount
方法-这是正确的行为吗?
import Bar from './Bar.jsx';
export default class Foo extends Component {
render() {
return (
<Bar />
);
}
}
Note: I have asked this question to sanity check the expected behaviour, in order to track down a bug. 注意:我问这个问题是为了检查预期的行为,以便找出错误。
The children behaviour depends on the parent behaviour. 孩子的行为取决于父母的行为。
componentDidMount() is invoked immediately after a component is mounted. 挂载组件后立即调用componentDidMount()。 The componentDidMount() method of child components is invoked before that of parent components.
在父组件之前调用子组件的componentDidMount()方法。
If your parent component simply re-renders, it is expected that child components also simply re-render, since componentDidMount() is invoked only once in the component's lifecycle. 如果父组件只是简单地重新渲染,则子组件也应该简单地重新渲染,因为componentDidMount()在组件的生命周期中仅被调用一次。
Need to be careful when using if if/else
logic in the render function. 在render函数中使用if
if/else
逻辑时,请务必小心。 In the example below, the Bar
component will unmount if the loading
prop value changes to true
: 在下面的示例中,如果
loading
属性值更改为true
,则Bar
组件将卸载:
import Bar from './Bar.jsx';
export default class Foo extends Component {
render() {
if(this.props.loading){
return (
<div>Loading...</div>
);
}
else{
return (
<Bar />
);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.