简体   繁体   中英

componentDidUpdate vs componentDidMount

I need to make sure an input element is focused when the following is true:

  • the DOM is available and
  • properties got changed

Question: Do I need to put my code in both componentDidUpdate and componentDidMount or just componentDidUpdate would be suffice?

    private makeSureInputElementFocused() {
        if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
            this.inputElement.focus();
        }

    }

    componentDidMount() {
        this.makeSureInputElementFocused(); // <-- do i need this?
    }
    componentDidUpdate() {
        this.makeSureInputElementFocused();
    }

You have to use both.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

componentDidUpdate()

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render .

You also could place it into the render() method which seems like it's appropriate for your case since you always want to check the focus. Then you don't need to put it into componentDidMount() and componentDidUpdate()

Each of your conditions require you to place the code inside 1 function each:

  • the DOM is available and - componentDidMount
  • properties got changed - componentDidUpdate

So you have to place inside both functions.
Another option is to call setState() inside componentDidMount , so that componentDidUpdate is invoked.

在初始渲染时不会调用componentDidUpdate (请参阅https://reactjs.org/docs/react-component.html#componentdidupdate ),因此您可能必须像示例中一样调用它两次。

componentDidMount()

componentDidMount() will be rendered immediately after a component is mounted. This method will render only once and all the initialization that requires DOM nodes should go here. Setting state in this method will trigger a re-rendering.

componentDidUpdate()

componentDidUpdate() is invoked immediately every time the updating occurs. This method is not called for the initial render.

You can understands more from this below example

import React from 'react';

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

    //This function will call on initial rendering.
    document.title = `You clicked ${this.state.count} times`;

  }
  componentDidUpdate() {
     document.title = `You clicked ${this.state.count} times`;
   }

  render(){
    return(
      <div>
      <p>You clicked {this.state.count} times</p>
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Click me
      </button>
    </div>
    )
  }
}
export default Example;

You can understand by commenting and un-commenting both methods.

In React v16.7.0-alpha you can use the useEffect hook:

import React, { useEffect, useRef } from "react";

function InputField() {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  });

  return <input ref={inputRef} />;
}

From the docs :

If you're familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Example

Note: as mentioned, this will not work with class based components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM