简体   繁体   English

如何使用 React 钩子中的 useState 添加/更新数组部门

[英]How to add/update the array department using the useState in react hook

I have a problem, I'm trying to add/update the data object after selecting an item.我有一个问题,我正在尝试在选择一个项目后添加/更新数据 object。

here's the code:这是代码:

const [roomDept, setDept] = useState([{ code: null, dept: null }]);
const [department, setDepartment] = useState([]);

const appendRoomDpt = () => {
  setRoomDept(array => [...array, { code: null, dept: null }]);
}
return (
  <div>
    <ButtonGroup>
      <IconButton icon={<Icon icon="plus" />} onClick={() => appendRoomDept()} />
    </ButtonGroup>
roomDept.map((item, index) => (
    <div key={index} className="flex">
      <div className="flex-1 pb-2">
        <SelectPicker
          placeholder={"Select Room"}
          data={room['data']}
          labelKey="name"
          valueKey="code"
          style={{ width: '120px' }}
          cleanable={false}
          disabledItemValues={roomDept.map(x => x.code)}
          onChange={(value) => {
            const id = room['data'].filter(x => x.code === value).map(x => x.id);
            (function getDepartment() {
              useDepartments.getAll({ room: id, length: 9999 }).then(response => {

                //Here's what I'm trying to do

                let dept = [...department];
                dept[index] = response['data']['data']
                setDepartment(department);
                console.log(department)

              });
            })()
          }}
          value={roomDept[index].code}
        />
      </div>

    </div>
    ))
  </div>
)

assuming roomDept I click the button add.假设roomDept我点击按钮添加。 then there's a two selection.然后有两个选择。 after that when I try to select on the first select field it will append on the department, but when I try to select on the second field it will just replace instead of adding.之后,当我尝试在第一个 select 字段上输入 select 时,部门将输入 append,但是当我在第二个字段上尝试输入 select 时,它只会替换而不是添加。 for example例如

I select on the first select field.我 select 在第一个 select 字段上。 the output is like this. output 是这样的。

[{code: 'r1', name: 'room 1'}]

then when I try to select on the second select field the output just replace on it然后当我在第二个 select 字段上尝试 select 时,output 只需替换它

[{code: 'r2', name: 'room2'}]

instead it will add, where it should be like this.相反,它会添加,它应该是这样的。

[{code: 'r1', name: 'room 1'},{code: 'r2', name: 'room2'}]

on the update side it should update base on the index and it will not add/append.在更新方面,它应该根据索引进行更新,并且不会添加/追加。

Always remember these three lines to update a state that stores an array永远记住这三行来更新一个存储数组的state

Break object to create a new one.打破 object 来创建一个新的。 Update that new object with the new value.使用新值更新新的 object。 setState with that new object.使用新的 object 设置状态。

It goes like so:它是这样的:

let newObj = { ...state }
newObj.keyToBeUpdated = updatedArray
setState(newObj)

That's it.就是这样。

Since you are trying to essentially update the state, could you just concat the original state array with the new one on click?由于您正在尝试从本质上更新 state,您能否在单击时将原始 state 数组与新数组连接起来? Something along the lines of:类似的东西:

const appendRoomDpt = (array) => {
    setRoomDept( [...roomDept,...array]);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM