为什么在重新渲染时没有调用componentDidMount?

joe*_*mow 0 reactjs

我有多个用于注册的模式,并且遇到问题.我总共有三个动作.首先是注册按钮,然后激活第一个注册模式以便用google或facebook注册,然后在完成之后,提供者无法收集的其他信息的模式将出现在预先填写的输入聚集形式提供者.我渲染应用程序时渲染两个模态,仅在单击注册按钮时显示它.我需要在完成facebook或google登录后调用componentDidMount,但是当我在app拳头开始时渲染模态时调用它.按钮命中动作减速器和减速器改变类型bool的状态以显示模态或不显示模态.

class HeaderRegisterButton extends Component {
   render() {
     return(
       <div>
         <Register1/>
         <Register2/>
       </div>
     );
   }
 }
Run Code Online (Sandbox Code Playgroud)

注册模式1

class Register1 extends Component {
   render() {
     return(
       <div>
        <button onClick={() => this.props.showRegister2()} /> //This would hit the action reducer to get initial info and change the bool to show register 1 to false and register 2 to true.
       </div>
     );
   }
 }
Run Code Online (Sandbox Code Playgroud)

注册模态2

import { reduxForm, Field, initialize } from 'redux-form';

class Register2 extends Component {

  componentDidMount() {
    hInitalize() //only called when the app fires, not when the state changes in the action reducer to change bool to show this modal.
  }

  hInitalize() {
   var initData = {};
  const initData = {
   "name" = this.props.name//name stored inside redux store
  };
  this.props.initialize(initData)
  }



   render() {
     return(
       <div> 
        //Code to display the modal which works.
       </div>
     );
   }
 }
Run Code Online (Sandbox Code Playgroud)

Gur*_*ngh 16

componentDidMount只在任何组件的生命周期中调用一次,重新渲染不会重新初始化组件.componentDidUpdate将被调用,您可以在其中管理您的逻辑.


Ali*_*mad 14

componentDidMount只会在 React 组件挂载时执行一次,并且不会在 state 或 props 更改时执行。

因此,您需要使用componentDidUpdate并且不要忘记比较 props 或 state(您也可以在父组件中的 props 更改时使用它)

  componentDidUpdate(prevProps,prevState) {
      if (this.state.userID !== prevState.userID) {
      console.log('userId changed');
   }
 }
Run Code Online (Sandbox Code Playgroud)

重要:不要在没有将其包装在条件中的情况下更新 componentDidUpdate 中的状态,因为这会触发重新渲染并且会导致无限循环