如果任何基于 class 的父组件接收到新道具但没有设置状态...它是否会调用 componentDidMount()

if any parent class based component receive new props but didnt setstate ...is it will call the componentDidMount()

我学习了过去 3 个月的反应,但没有清楚地了解 1 件事..我想知道如果我的顶级应用程序组件获得新道具但没有调用任何设置状态...是吗要调用组件 Did Mount 吗?或者它不会调用任何组件 D​​id Mount..

如果组件已经挂载,它不会再调用componentDidMount,不会。但它会(暂时)调用旧的 componentWillReceiveProps/UNSAFE_componentWillReceiveProps, and will call render and componentDidUpdate.

尝试这些东西很容易。例如:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log("Parent - constructor");
    }

    componentDidMount() {
        console.log("Parent - componentDidMount");
    }

    UNSAFE_componentDidReceiveProps() {
        console.log("Parent - UNSAFE_componentDidReceiveProps");
    }

    componentDidUpdate() {
        console.log("Parent - componentDidUpdate");
    }

    render() {
        console.log("Parent - render");
        const { value } = this.props;
        return <Child value={value} />;
    }
}

class Child extends React.Component {
    constructor(props) {
        super(props);
        console.log("Child - constructor");
    }

    componentDidMount() {
        console.log("Child - componentDidMount");
    }

    UNSAFE_componentDidReceiveProps() {
        console.log("Child - UNSAFE_componentDidReceiveProps");
    }

    componentDidUpdate() {
        console.log("Child - componentDidUpdate");
    }

    render() {
        console.log("Child - render");
        const { value } = this.props;
        return <div>value = {value}</div>;
    }
}

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0
        };
    }

    componentDidMount() {
        setTimeout(() => {
            this.timer = setInterval(() => {
                this.setState(({counter}) => {
                    ++counter;
                    if (counter === 2) {
                        clearInterval(this.timer);
                    }
                    return {counter};
                });
            }, 500);
        }, 1000);
    }

    render() {
        const { counter } = this.state;
        return <Parent value={counter} />;
    }
}

ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>