繁体   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