简体   繁体   中英

Child component value not updating after set state

I am attempting to update properties on a parent object via button clicks in the child components. After clicking the increment button neither of the child components get updated.

NOTE: id is purely to differentiate between propA and B for saving state

Also is there a nice way to deal updating object properties without having to do a switch statement

Minimum reproduction

import { useState } from "react";
import "./styles.css";

export default function App() {
  let [object, setObject] = useState({
    propertyA: 0,
    propertyB: 0
  });

  function handleClick(id) {
    switch (id) {
      case 1:
        setObject((prevState) => ({
          ...prevState,
          propertyA: prevState.propertyA + 1
        }));
        break;
      case 2:
        setObject((prevState) => ({
          ...prevState,
          propertyB: prevState.propertyB + 1
        }));
        break;
      default:
        console.log(id);
        break;
    }
  }

  return (
    <div className="App">
      <Child
        id="1"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
      <Child
        id="2"
        title="property B"
        value={object.propertyB}
        handleClick={handleClick}
      />
    </div>
  );
}

function Child(props) {
  return (
    <div>
      {props.title} : {props.value}
      <button onClick={props.handleClick(props.id)}>Increment</button>
    </div>
  );
}

onClick={props.handleClick(props.id)} should be onClick={()=>props.handleClick(props.id)} , and for the avoiding switch you can set the id as the property name

 <Child
        id="propertyA"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />

and then

function handleClick(id) {
  setObject((prevState) => ({
          ...prevState,
         [id]: prevState[id] + 1
        }))
}

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