You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React子组件getDerivedStateFromProps点击按钮后触发两次的问题咨询

Why 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:

  1. The Parent component calls setState, updating its count state.
  2. This triggers a re-render of the Parent, which passes the new count value as a prop to the Child.
  3. The Child's props change, so React initiates an update cycle for the Child.
  4. In development Strict Mode, React calls getDerivedStateFromProps twice to verify the function is pure (same input always produces the same output, no hidden side effects).
  5. That's why you see child Derived logged 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 props and state.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:47:57