【发布时间】: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