React子组件getDerivedStateFromProps点击按钮后触发两次的问题咨询
getDerivedStateFromProps is Triggered Twice in Your Child Component Hey there! I totally get your confusion—seeing that child Derived log twice when you expect it once is definitely head-scratching. Let's break down what's happening here.
The Root Cause: React Strict Mode
The most likely reason you're seeing two logs is that your app is running in React Strict Mode (in the development environment).
React Strict Mode is a debugging tool that helps catch potential issues in your code early. In development mode, it intentionally double-invokes certain lifecycle methods (including getDerivedStateFromProps, render, and a few others) to flag impure functions or unintended side effects.
This is strictly a development-only behavior—it won't happen in production, where the method will run only once per update just like you expected.
Let's Walk Through Your Code Flow
When you click the button:
- The Parent component calls
setState, updating itscountstate. - This triggers a re-render of the Parent, which passes the new
countvalue as a prop to the Child. - The Child's props change, so React initiates an update cycle for the Child.
- In development Strict Mode, React calls
getDerivedStateFromPropstwice to verify the function is pure (same input always produces the same output, no hidden side effects). - That's why you see
child Derivedlogged twice.
How to Confirm This
Check your root component rendering code—if it looks like this (React 17 or earlier):
ReactDOM.render( <React.StrictMode> <Parent /> </React.StrictMode>, document.getElementById('root') );
Or like this (React 18):
const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Parent /> </React.StrictMode> );
Then Strict Mode is enabled. If you temporarily remove the <React.StrictMode> wrapper, you'll see the log only once in development (though I recommend keeping Strict Mode enabled long-term—it helps write more robust React code).
Key Best Practice for getDerivedStateFromProps
Remember that getDerivedStateFromProps is meant to be a pure function:
- It should only calculate and return a new state based on the given
propsandstate. - It shouldn't include any side effects (like API calls, modifying external variables, or even
console.log—though logs are harmless, they make the double-invocation obvious).
React may call this method multiple times in specific scenarios (like Strict Mode), so keeping it pure ensures your component behaves consistently no matter what.
内容的提问来源于stack exchange,提问作者die

