我正在尝试在安装周期中初始化状态,然后在每次更新时对其进行处理。
但是,状态以某种方式重置?我不明白为什么。
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 []
最佳答案
我设法用 useRef
以一种奇怪的方式解决了它对于函数变量,并通过将函数定义移动到 useEffect
?
const [journalItems, setJournalItems] = useState([]);
let handleTableRowClick = useRef(null);
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.current(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
handleTableRowClick.current = (journalItemId) => {
console.log("handletablerowclick journalItems", journalItems)
// Find the clicked row from all the rows
let journalItem = journalItems.filter(item => item.id === journalItemId)[0]
setFormJournalItems(journalItem)
}
}, [journalItems]);
关于javascript - useState hook - 状态丢失,即重置为初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60348933/