Home > Blockchain >  When react really updated real dom in lifecycle
When react really updated real dom in lifecycle

Time:12-26

When React updated dom in browser?

Reproduction


The first time

render methods, in this time, document.getElementById show null


The second time updated,

document.getElementById get new DOM

I expected it should get old DOM, but document.getElementById get new one.


In lifecycles diagram, it show ­React updates ­D­O­M after render, so I think

document.getElementById should take old dom.

CodePudding user response:

document.getElementById at first returns null because your are trying to get the element before rendering it thus it does not exist at the moment. The second time the component has mounted and thus an element with an id of #a exist and is returned.

If you want to get the previous state, you can use this:

this.setState((prevState, pros) => {
    // your code here.
});

CodePudding user response:

After render() method called, the render process occurs.

It means #a only created when you return <div>...</div>

Let's see your code

  render() {
    console.log("render");

    // => 1. you want to find #a but it not rendered yet
    // so result is undefined
    console.log(document.getElementById("a")); 


    // 2. #a rendered at this line, not above
    return (<div>....</div>); 
  }

Try to wait 100ms and print #a again

  render() {

    // 1. wait to 100ms
    setTimeout(() => {
      // => 3. now, you found #a, because after 100ms it rendered already
      console.log(document.getElementById("a"));   
    }, 100)

    // 2. #a rendered at this line
    return (<div>....</div>); 
  }
  • Related