反应数组中元素的Hooks setState [英] React Hooks setState of an element in an array

查看:67
本文介绍了反应数组中元素的Hooks setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更新状态数组中的单个元素?这是我当前正在使用的代码:

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>
  )
};

当我单击呈现的按钮之一时,出现未捕获的TypeError:setCars [0]不是handleClick1上的函数.

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

我知道如何在React类中做到这一点,但是如何使用React Hooks做到这一点?

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

推荐答案

我建议您在您的汽车中进行地图绘制以进行渲染-总体而言,这要容易上百万倍.从那里,您可以将 onClick 处理程序应用于每个按钮.

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.

我之前没有想到的一件事是,当您成为 map key >遍历数组.这应该是标准做法.

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.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>

这篇关于反应数组中元素的Hooks setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆