javascript - useState hook - 状态丢失,即重置为初始值

标签 javascript reactjs react-hooks use-effect

我正在尝试在安装周期中初始化状态,然后在每次更新时对其进行处理。

但是,状态以某种方式重置?我不明白为什么。

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/

相关文章:

javascript - 为什么 'abc' .toString() 给出的结果与 toString.call ('abc' 不同)?

javascript - createElement 函数不适用于 MAC Safari

node.js - 使用 axios 调用登录 API 时,当我的凭据在 catch 中错误时,我没有收到任何响应

javascript - requirejs:有没有办法设置多个位置来搜索 1 个资源

javascript - 如何优化这些 jquery 函数?

node.js - 错误 : Cannot find module 'browserslist' when I run the npm run build

javascript - react renderToString 不渲染 js

javascript - 使用 for-each 和 props 更改状态值

react-native - 获取 FlatList 的当前索引/可见项

javascript - 如何在jest和enzyme中设置useState Hook的初始状态?