【发布时间】:2020-02-22 13:07:47
【问题描述】:
我正在尝试在安装周期中初始化状态,然后在每次更新时对其进行处理。
但是,状态会以某种方式重置?我不明白为什么。
const [journalItems, setJournalItems] = useState([]);
useEffect(() => {
fetch(`http://localhost:4000/journals/${props.match.params.key}/items`)
.then(res => res.json())
.then(data => {
setJournalItems(data) // Sets the state when the AJAX completes
})
.catch(err => err);
table.current = new Tabulator(refTable.current, {
rowClick: function (e, row) {
console.log("tabulator journalitems", journalItems) // State is lost returns []
handleTableRowClick(row._row.data.id)
},
columns: [
{ title: "Компанија", field: "companyName" },
{ title: "Документ", field: "documentKey" },
],
});
}, []);
useEffect(() => {
console.log("useEffect journalItems", journalItems) // Works fine
table.current.replaceData(journalItems) // Uses the new state
}, [journalItems]);
function handleTableRowClick(journalItemId) {
console.log("handletablerowclick journalitems", journalItems) // State is lost, resets to []
}
结果来自控制台日志...
useEffect journalItems []
useEffect journalItems (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
tabulator journalitems []
handleTableRowClick journalitems []
【问题讨论】:
-
您查看控制台日志的次数是多少?当组件挂载时,带有依赖关系的
useEffect实际上仍然会触发,就像它对[]所做的那样。因此,我希望看到一个带有空数组的日志,然后如果您的更新成功,则会看到第二个。 -
是的,我确实看过两次。 1.
useEffect journalItems [],2.useEffect journalItems (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]。但是,点击处理程序中的状态为空... -
好的,你的更新让问题更清楚了。
-
我正在阅读possible solution here,但为什么会发生这种情况是没有意义的......
-
@Ivan,也许这可以帮助你stackoverflow.com/questions/54069253/…。状态变化是异步的。
标签: javascript reactjs react-hooks use-effect