facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
229.31k stars 46.96k forks source link

Bug: after upgrade v18 "componentDidMount" run twice, and componentWillUnmount also run when component mounting #24255

Closed awefeng closed 2 years ago

awefeng commented 2 years ago

React version: v18.0.0

Steps To Reproduce

  1. write a class component
  2. write "componentDidMount" and "componentWillUnmount" lifecycle functions,log a tip
    componentDidMount() {
    console.log("componentDidMount");
    }
    componentWillUnmount() {
    console.log("componentWillUnmount");
    }

Link to code example: https://codesandbox.io/s/stoic-snowflake-pwih7o

The current behavior

the console print componentDidMount ->componentWillUnmount -> componentDidMount

The expected behavior

only run componentDidMount once

awefeng commented 2 years ago

this is a v17.0.2 example https://codesandbox.io/s/runtime-brook-z67gx3

GLObus303 commented 2 years ago

That's a new behaviour inside StrictMode - https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

gaearon commented 2 years ago

Yes, this is a development-only change in Strict Mode described here. You can opt out of Strict Mode while upgrading if this breaks your code and then fix the issues later.

https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

awefeng commented 2 years ago

That's a new behaviour inside StrictMode - https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

maybe I should take a good look at the update docs,thank you bro

awefeng commented 2 years ago

Yes, this is a development-only change in Strict Mode described here. You can opt out of Strict Mode while upgrading if this breaks your code and then fix the issues later.

https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

thank you bro