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

如何修改React基础计数器使多个组件实例保持相同数值

Solution to Sync Multiple React Counter Instances

Got it! Right now each Counter component keeps its own separate state, which is why they don’t update together. To make all counters sync their values in real-time, we need to lift the shared state up to their parent component (App)—this way, all counters rely on the same source of truth, and any update will reflect across all instances.

Here’s how to adjust your code:

Step 1: Update the App Component

Move the counter state, action state, and the handleCounter function from Counter to App. Then pass these values and functions down as props to each Counter instance:

import React, { useState } from "react";
import './App.css';
import Counter from "./Counter";

function App () {
  // Shared state for all counters
  const [counter, setCounter] = useState(0);
  const [action, setAction] = useState("");

  const handleCounter = (increase, amount) => {
    // Use functional update to ensure we get the latest state value
    setCounter(prevCounter => prevCounter + (increase ? amount : -amount));
    setAction(increase ? "increased" : "decreased");
  }

  return (
    <div className="App">
      <h1>A BASIC COUNTER</h1>
      {/* Pass shared state and handler as props to each Counter */}
      <Counter counter={counter} action={action} handleCounter={handleCounter} />
      <Counter counter={counter} action={action} handleCounter={handleCounter} />
      <Counter counter={counter} action={action} handleCounter={handleCounter} />
    </div>
  );
}

export default App;

Step 2: Update the Counter Component

Remove the local state from Counter—instead, use the props passed down from App. This turns it into a presentational component that just renders the data it receives:

import React from "react";

// Destructure props directly in the component parameters
function Counter({ counter, action, handleCounter }) {
  return (
    <>
      <h1>{counter}</h1>
      <h2>{action}</h2> {/* Switched to h2 for better heading hierarchy (optional) */}
      <div>
        <button onClick={() => handleCounter(true, 1)}>increase +1</button>
        <button onClick={() => handleCounter(false, 1)}>decrease -1</button>
        <button onClick={() => handleCounter(true, 10)}>increase +10</button>
        <button onClick={() => handleCounter(false, 10)}>decrease -10</button>
      </div>
    </>
  );
}

export default Counter;

Why This Works

  • All Counter instances now use the same state managed by the App component. When any button is clicked, it triggers handleCounter in App, which updates the shared counter and action state.
  • React automatically re-renders all Counter components with the new state values, so every counter shows the exact same number and action at the same time.

Quick Note

I used a functional update (setCounter(prevCounter => ...)) instead of directly referencing counter in the update. This is a safe practice to ensure we always use the most recent state value, especially if there are multiple rapid updates.

内容的提问来源于stack exchange,提问作者user15243442

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:57:36