简体   繁体   中英

React Hooks setState of an element in an array

How can I update a single element in a state array? Here is the code that I am currently using:

const Cars = props => {
  const [cars, setCars] = React.useState(["Honda","Toyota","Dodge"])

  const handleClick1 = () => { setCars[0]("Jeep") }
  const handleClick2 = () => { setCars[1]("Jeep") }
  const handleClick3 = () => { setCars[2]("Jeep") }

  return (
    <div>
      <button onClick={handleClick1}>{cars[0]}</button>
      <button onClick={handleClick2}>{cars[1]}</button>
      <button onClick={handleClick3}>{cars[2]}</button>
    </div>
  )
};

When I click one of the rendered buttons, I get Uncaught TypeError: setCars[0] is not a function at handleClick1 .

I know how to do this in a React Class, but how can I do this with React Hooks?

I suggest you map through your cars in order to render them - this is just overall a million times easier. From there you can apply an onClick handler to each button..

Furthermore, you should not mutate state like you are - always make a copy of state first, update the copy, then set your new state with the updated copy.

Edit: one thing that slipped my mind before was adding a key to each item when you are map ping over an array. This should be standard practice.

 const { useState } = React; const { render } = ReactDOM; const Cars = props => { const [cars, setCars] = useState(["Honda", "Toyota", "Dodge"]); const updateCars = (value, index) => () => { let carsCopy = [...cars]; carsCopy[index] = value; setCars(carsCopy); }; return ( <div> {cars && cars.map((c, i) => <button key={`${i}_${c}`} onClick={updateCars("Jeep", i)}>{c}</button> )} <pre>{cars && JSON.stringify(cars, null, 2)}</pre> </div> ); }; render(<Cars />, document.body);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>

I think you should correct these lines to spot the source of error

const handleClick1 = () => { setCars[0]("Jeep") }

into

const handleClick1 = () => { cars[0]="Jeep"; setCars(cars); }

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