最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hooks setState of an element in an array - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Nov 1, 2020 at 18:46 Ibraheem Ahmed asked Dec 14, 2019 at 20:30 Ibraheem AhmedIbraheem Ahmed 13.5k2 gold badges55 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

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 mapping 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./ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./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); }
发布评论

评论列表(0)

  1. 暂无评论