如何修改React基础计数器使多个组件实例保持相同数值
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
Counterinstances now use the same state managed by theAppcomponent. When any button is clicked, it triggershandleCounterinApp, which updates the sharedcounterandactionstate. - React automatically re-renders all
Countercomponents 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

