【问题标题】:What's the way to update dynamic state using React hooks?使用 React 钩子更新动态状态的方法是什么?
【发布时间】:2020-02-05 11:46:39
【问题描述】:

我正在尝试将我的代码更新为 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 函数的方式:

        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)
            ]
        });
}

【问题讨论】:

  • 请在您使用钩子的地方显示您的代码。
  • 我添加了我的代码
  • 那么到底是什么不工作是数据没有保存到状态,或者你错过了状态中的一些数据?
  • 我的表在数据提取时没有更新

标签: javascript reactjs react-hooks


【解决方案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
      })
    }
  });
}

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多