React useState如何修改数组中的第一个对象

时间:2020-08-03 19:27:48

标签: reactjs react-hooks

SANDBOX LINK

我正在使用FormControl来更新默认为const [numberOfChildren, updateNumberOfChildren] = useState([{age: undefined}]);的状态。我想在用户单击按钮时修改数组中的第一个对象,然后在输入。我尝试用另一个age更新useState,目前,数组的第一个对象是{age: undefined},并且没有被useState钩子更新

代码看起来像这样

 <FormControl
 placeholder="Age"
 aria-label="Age"
 aria-describedby="basic-addon2"
 onChange={async (e) => {
       await updateAge(e.target.value);
 }}
 />

通过按钮更新

<Button
  className="align-button"
  onClick={async (e) => {
         e.preventDefault();
         if(numberOfChildren.length < 1) {
                   await updateNumberOfChildren((children) => [
                         ...children
                   ]);
                   } else {
                      await updateNumberOfChildren((children) => [
                       ...children,
                         { childAge: age },
                       ]);
                       }

                        console.log(numberOfChildren)
                            }}
                            style={{ width: "100%" }}
                            variant="outline-primary"
                            type="submit"
                            size="lg"
                        >
                            Add Child
                        </Button>{" "}

这是一个沙箱,请查看控制台输出SANDBOX

1 个答案:

答案 0 :(得分:1)

使用 //in action get id groups and group with id users // { // type: 'UPDATE_GROUP', // id: '1A', // group: [ // '1' // ] // } switch (action.type) { case UPDATE_GROUP: return { ...state, shop: { ...state.shop, groups: state.shop.groups ???? } }; default: return state; } }``` 进行操作的方式不会获得您想要的,因为这样做只会更新最新添加的子项,因此您无法返回第一个子项并进行修改或甚至在添加完以前的所有子项之后都对其进行修改,因为当前设置无法区分要修改的子项。

所以,这里的想法是您需要用唯一的东西来标识数组中的每个对象,因此我将对象结构更改为以下内容:

const [age, updateAge] = useState(undefined);

这是更新状态的方式,解释每一行:

const [numberOfChildren, updateNumberOfChildren] = useState([
        { id: 1, age: undefined }
      ]);

当您添加一个新孩子时,最新添加的孩子将具有// Update numberOfChildren state function updateData(e) { // Grab the id of the input element and the typed value const { id, value } = e.target; // Find the item in the array that has the same id // Convert the grabed id from string to Number const itemIndex = numberOfChildren.findIndex( item => item.id === Number(id) ); // If the itemIndex is -1 that means it doesn't exist in the array if (itemIndex !== -1) { // Make a copy of the state const children = [...numberOfChildren]; // The child item const child = children[itemIndex]; // Update the child's age children.splice(itemIndex, 1, { ...child, age: value }); // Update the state updateNumberOfChildren(children); } } 状态长度的ID加1,因为我以1为起点:

numberOfChildren

最后,如果要检查任何状态值,请不要在onClick={e => { e.preventDefault(); updateNumberOfChildren([ ...numberOfChildren, { id: numberOfChildren.length + 1, age: undefined } ]); }} 之后使用console.log(),因为setState()setState(),因此不会立即得到更改,并且因为使用钩子的唯一方法是async

useEffect()

这里是sandbox。希望现在一切都变得清晰起来。