React componentDidUpdate()不会触发

问题描述 投票:0回答:2

我有一个安装了primereact的react应用,并且我正在使用primereact /验证码。

也许我误解了一些东西,但是下面的代码不应该起作用吗?(console.log('Child component did update''])?

import React from 'react';
import { Captcha } from 'primereact/captcha';

export default function App() {
  return (
    <div className="App">
      <ParentComponent/>
    </div>
  );
}

class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (<h2>Child component</h2>);
    }
}

class ParentComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            captchaSovled: false,
            key : Math.random()
        }
    }
    render() {
        let output;
        if (this.state.captchaSolved) {
            output = <Child key={this.state.key} />;
        } else {
            output =<Captcha siteKey="xxxxxxx" onResponse={() => this.setState({ key : Math.random(), captchaSolved: true })} />
        }
        return (
            <div>
                <h1>Parent component</h1>
                {output}
            </div>
        );
    }
}
reactjs
2个回答
0
投票

componentDidUpdate被触发,如果stateprops有任何变化。从组件child开始:

class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (<h2>Child component</h2>);
    }
}

[stateprops没有变化,这就是componentDidUpdate从未被调用的原因。


0
投票

来自React doc

componentDidUpdate()在更新发生后立即被调用。初始渲染未调用此方法。

在您的代码中,在设置了Child状态之后就安装了captchaSolved组件,因此在componentDidMount组件上仅触发了Child

© www.soinside.com 2019 - 2024. All rights reserved.