使用数组从对象的反应状态更新选定的 属性

Update a selected property from react state of objects with arrays

假设这个状态有这样的初始数据

const [options, setOptions] = useState({
  ProcessType: [
    { value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
  ],
  ResponsibleUser: [
    { value: 1, label: 'User1' }, { value: 2, label: 'User2' }
  ]
});

当post/put调用

时,以下函数将被一次又一次地调用

帮我完成那里描述的评论区。

const fetchProcesses = async () => {
  await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
    .then((result) => {
      /* 
        I want here to clear the existing data in options.ProcessType and
        map result.data as { value: result.data.id , label: result.data.name },....
        and push/concat it into to options.ProcessType but i want to keep the data
        inside options.ResponsibleUser unchanged. 
  
        result.data is an array of objects like this,
        [
          { id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
          { id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
          .....
          .....
        ]
      */
    })
}

这是一个解决方案

const fetchProcesses = async () => {
    await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
      .then((result) => {
        // solution
        setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType:  result.data.map(row => ({value: row.id, label: row.name}))})
    })
}