如何在React Hook状态下正确更新数组 [英] How to properly update an array inside a react hook state

查看:636
本文介绍了如何在React Hook状态下正确更新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试更新表示反应状态的数组中的对象,当输入值更改时应该更新该对象,我可以自己找到一种更新它的方法,但是我没有足够确定这是执行此操作的正确方法,因为当我打开react开发工具并转到组件"选项卡并单击我正在处理的组件时,输入输入时状态不会立即更新,并且为了查看更改,我必须在开发工具中单击另一个组件,然后返回到第一个组件,更改已完成.

i've been trying to update the object inside an array that respresents a react state, the object should be updated when the value of an input is changed, I could find a way myself to update it, but i'm not sure enough that it is the proper way to do it because when i open the react dev tools and go to the components tab and click the component that i'm working on, the state doesn't update immidiatly when typing in the input, and in order to see the change i have to click on another component in the dev tool and then go back to the first component and the change is done.

所以我基本上是在问我用来更新状态的方法是否正确,并获得一些更好的建议来做到这一点,以便它可以立即更新.谢谢

So I'm basically asking if the way i used to update the state is correct and to get some suggestions about better ways to do it so it updates instantly. Thanks

这是代码

状态:

const [items, setItems] = useState([{ name: "", quantity: "", unit: "" }]);

变更处理功能(更新状态的功能):

the change handling function (the function that updates the state):

const nameChange = (e, i) => {
  const newItems = items;
  newItems[i].name = e.target.value;
  setItems(newItems);
  console.log(items);
};

输入:

{
  items.map((item, i) => {
    return (
      <div key={i} className={`mt3 ${classes.root}`}>
        <TextField
          onChange={e => nameChange(e, i)}
          style={{ width: "30%" }}
          id="standard-basic"
          label="Item name"
        />
        <TextField
          style={{ width: "25%" }}
          id="standard-basic"
          label="quantity"
        />
        <TextField
          style={{ width: "10%" }}
          id="standard-basic"
          label="Unit"
        />
      </div>
    );
  });
}

推荐答案

    const [items, setItems] = React.useState({
        name: '',
        quantity: '',
        unit: ''
    });
    const handleChange = prop => event => {
        setItems({ ...items, [prop]: event.target.value });
    };

在您的文本字段上:

    <TextField onChange={handleChange('name')}/>
    <TextField onChange={handleChange('quantity')}/>

更新:如果项目是数组:

    const updateItem = (prop, event, index) => {
        const old = items[index];
        const updated = { ...old, [prop]: event.target.value }
        const clone = [...items];
        clone[index] = updated;
        setItems(clone);
    }

在您的文本字段上:

{items.map((item, i) => (
    <div key={i}>
        <TextField onChange={e => updateItem('name', e, i)}/>
        <TextField onChange={e => updateItem('quantity', e, i)}/>
        <TextField onChange={e => updateItem('unit', e, i)}/>
    </div>
))}

这篇关于如何在React Hook状态下正确更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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