简体   繁体   中英

How can I lift up the state from Child to Parent in my React app?

I need to lift up the state of my Child component to the Parent to be able to reset this within the resetTotals() function. Each child component within the map has a click counter, so this needs to be reset within the parent component onClick.

How can I pass up the state?

// Parent Functional Component

function Parent() {
  const [calorieCount, setCalorieCount] = useState(0);
  const [vitaminACount, setVitaminACount] = useState(0);
  const [vitaminDCount, setVitaminDCount] = useState(0);

  function updateTotals(calories = 0, vitaminA = 0, vitaminD = 0) {
    setCalorieCount(prevCalorieCount => Math.round(prevCalorieCount + calories));
    setVitaminACount(prevVitaminACount => Math.round((prevVitaminACount + vitaminA) * 100) / 100);
    setVitaminDCount(prevVitaminDCount => Math.round((prevVitaminDCount + vitaminD) * 100) / 100);
  }

  function resetTotals() {
    setCalorieCount(0);
    setVitaminACount(0);
    setVitaminDCount(0);
  }

  return (
    <div className="App">

      <main className="products-grid flex flex-wrap">
        {FoodCards.map((item, i) => {
          return <Child 
          key={item.id} 
          name={item.name} 
          img={item.img}
          calories={item.calories} 
          vitamin_a={item.vitamin_a} 
          vitamin_d={item.vitamin_d}
          updateTotals={updateTotals} />
        })}
      </main>

      <footer>
        <div
        className="reset" 
        onClick={() => resetTotals()}
        >Reset</div>
      </footer>
    </div>
  );
}
export default App

// Child Functional Component

const Child = (props) => {
      const [clickCount, setClickCount] = useState(0);
    
      function handleUpdateTotals(calories, vitamin_a, vitamin_d) {
        props.updateTotals(calories, vitamin_a, vitamin_d);
        setClickCount(prevClickCount => prevClickCount + 1);
      }
    
      return (
        <div 
        className="product"
        onClick={() => handleUpdateTotals(props.calories, props.vitamin_a, props.vitamin_d)}
        >
          <p>{props.name}</p>
          <p>{clickCount > 0 ? <p>Selected: {clickCount}</p> : <p>Not Selected</p>}</p>
          <img src={props.img} alt="" />
        </div>
      );
    }

You are already updating the parent state from the child in that code.

You are passing in a callback function as a property, then calling it by props.updateTotals() . That will then run the updateTotals function in parent.

Do the same for reset totals: pass the method in as a prop, and call it from the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM