React - 每次父组件呈现时,子组件是否重新挂载?
问题描述:
在这个非常基本的示例中,我将组件Bar
包含在组件Foo
的渲染函数中。我注意到Bar
的componentDidMount
方法在每次Foo重新渲染时都会触发 - 这是正确的行为吗?React - 每次父组件呈现时,子组件是否重新挂载?
import Bar from './Bar.jsx';
export default class Foo extends Component {
render() {
return (
<Bar />
);
}
}
注:我也问过这个问题,理智检查预期的行为,为了追踪一个错误。
答
孩子的行为取决于父母的行为。
componentDidMount()在组件装入后立即被调用。子组件的componentDidMount()方法在父组件之前被调用。
如果您的父组件简单地重新呈现,则期望子组件仅仅重新呈现,因为componentDidMount()在组件的生命周期中仅被调用一次。
答
在渲染功能中使用if/else
逻辑时需要小心。在下面的例子中,Bar
组件将卸载如果loading
道具值更改为true
:
import Bar from './Bar.jsx';
export default class Foo extends Component {
render() {
if(this.props.loading){
return (
<div>Loading...</div>
);
}
else{
return (
<Bar />
);
}
}
}
可否请你清理这个答案,将其取出约父重新安装细节,问题是只关心重新渲染(?) – JoeTidee
@JoeTidee完成。 – idjuradj