简体   繁体   English

React-子组件每次渲染时都会重新安装吗?

[英]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每次重新渲染时,都会触发BarcomponentDidMount方法-这是正确的行为吗?

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.

相关问题 是否可以在React中重新安装组件? - Is it possible to re-mount a component in React? 每次单击按钮时卸下并重新安装组件? - Dismount and re-mount a component on each button click? 使用 key prop 强制重新安装 React 组件 - Using the key prop to force re-mount of a React component React-router:更改查询字符串不会重新安装组件 - React-router: changing query string does not re-mount the component 更改路线后如何重新安装组件 - React how re-mount component after route change 路线变化时反作用力重新安装组件 - React force re-mount component on route change 在 React 中,如果子组件渲染,父组件是否也渲染? - In React, if a child component renders, does the parent component render too? 在重定向到具有不同特性的同一页面时,React Router触发触发器重新加载/重新安装组件 - React Router trigger re-load / re-mount component on redirecting to same page with different slug React-Router URL 在链接单击时导致组件重新安装(使用 useEffect(..)、[] 重新初始化) - React-Router URL Causes Component Re-Mount (Re-Initialization with useEffect(..), []) on Link Click 什么可能导致 React Native 组件不断地卸载和重新安装? - What might be causing a React Native component to continuously un- and re-mount?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM