簡體   English   中英

使用 React 鈎子更新動態狀態的方法是什么?

[英]What's the way to update dynamic state using React hooks?

我正在嘗試將我的代碼更新為 React Hooks。 我的函數是在響應后更新異步函數內的數據。 我試圖通過 React Hooks 做類似的解決方案,但它並沒有真正起作用。 這是為什么? 有什么辦法呢?

這是我的更新功能:

updateData = (id, itemAttributes, property) => {
    let prop = this.state[property];
    let index = prop.rows.findIndex(x => x.eventID === id);
    if (index === -1) {
        return null
    } else
      this.setState({
          [property]: {
            columns: prop.columns,
            rows: [
                ...prop.rows.slice(0,index),
                Object.assign({}, prop.rows[index], itemAttributes),
                ...prop.rows.slice(index+1)
             ]
          }
      });
}

這就是我獲取數據和使用 updateData func 的方式:

        this.state.data.rows.forEach((elem,index) => {
            setTimeout(async () => {
                const row = await axios.get(url);
                const elemInfo = {
                    eventRegistrants: row.data.numberOfRegistrants,
                    eventParticipants: row.data.numberOfParticipants
                }
                this.updateData(
                    elem.eventID, 
                    elemInfo,
                    'data'
                )
            }, index * 1000)
        })

編輯

這是我目前使用 React Hooks 不起作用的解決方案:

const updateData = (id, itemAttributes) => {
    let index = data.rows.findIndex(x => x.eventID === id);
    if (index === -1) {
        console.log('error');
    } else
        setData({
            columns: data.columns,
            rows: [
                ...data.rows.slice(0,index),
                Object.assign({}, data.rows[index], itemAttributes),
                ...data.rows.slice(index+1)
            ]
        });
}

嘗試使用setState的函數形式:

const updateData = (id, itemAttributes) => {
  setData(currData => {
    const index = currData.rows.findIndex(x => x.eventID === id);
    if (index === -1) {
      console.log('error');
    } else {
      return {
        ...currData,
        rows: [
          ...data.rows.slice(0, index),
          Object.assign({}, data.rows[index], itemAttributes),
          ...data.rows.slice(index + 1)
        ]
      }
    }
  });
}

另一種方法是使用map設置狀態,它更簡潔:

const updateData1 = (id, itemAttributes) => {
  setData(currData => {
    return {
      ...currData,
      rows: currData.rows.map(row => {
        if (row.eventID === id) {
          return {
            ...row,
            itemAttributes
          }
        }
        return row
      })
    }
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM