我如何在React Hooks中更新对象数组中的状态onchange [英] How do I update states onchange in an array of object in React Hooks

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

问题描述

我已经检索了使用useState存储在对象数组中的数据,然后将这些数据输出到表单字段中.现在,我希望能够在键入时更新字段(状态).

I have retrieved datas stored using useState in an array of object, the datas was then outputted into form fields. And now I want to be able to update the fields (state) as I type.

我似乎有一些例子可以说明人们为数组中的属性更新状态,但从未为对象数组中的状态更新状态,因此我不知道该怎么做.我已经将对象的索引传递给了回调函数,但是我不知道如何使用它来更新状态.

I have seem examples on people updating the state for property in array, but never for state in an array of object, so I don't know how to do it. I've got the index of the object passed to the callback function but I didn't know how to update the state using it.


// sample datas structure
const datas = [
    {
      id:   1,
      name: 'john',
      gender: 'm'
    }
    {
      id:   2,
      name: 'mary',
      gender: 'f'
    }
]

const [datas, setDatas] = useState([]);

const updateFieldChanged = index => e => {

    console.log('index: ' + index);
    console.log('property name: '+ e.target.name);

        setData() // ??
}

return (
    <React.Fragment>
        { datas.map( (data, index) => {
              <li key={data.name}>
                <input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)}  />
              </li>
          })
        }
    </React.Fragment>
)

推荐答案

操作方法如下:

// sample datas structure
/* const datas = [
    {
      id:   1,
      name: 'john',
      gender: 'm'
    }
    {
      id:   2,
      name: 'mary',
      gender: 'f'
    }
] */ // make sure to set the default value in the useState call (I already fixed it)

const [datas, setDatas] = useState([
    {
      id:   1,
      name: 'john',
      gender: 'm'
    }
    {
      id:   2,
      name: 'mary',
      gender: 'f'
    }
]);

const updateFieldChanged = index => e => {

    console.log('index: ' + index);
    console.log('property name: '+ e.target.name);
    let newArr = [...datas]; // copying the old datas array
    newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to

    setDatas(newArr); // ??
}

return (
    <React.Fragment>
        { datas.map( (data, index) => {
              <li key={data.name}>
                <input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)}  />
              </li>
          })
        }
    </React.Fragment>
)

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

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