首页 > 解决方案 > 为什么撤消变量没有更新?

问题描述

这是我的代码:

import useUndo from 'use-undo';
export default function UndoTable(props){
    const [hightLightCellIndex, setHightLightCellIndex] = useState(-1);
    let [
        rosterList,
        undoUtil
    ]=useUndo(props.rosterTableData.rosterList);
        
    let activeShiftInfoList=props.rosterTableData.shiftInfoList;
    let calendarUtility=props.rosterTableData.calendarUtility;
    let monthlyCalendar=props.rosterTableData.monthlyCalendar;
    let contextValue={
        activeShiftInfoList,
        calendarUtility,
        hightLightCellIndex,
        monthlyCalendar,
        rosterList,
        setHightLightCellIndex,
        undoUtil
    };    
    console.log(Object.keys(props.rosterTableData.rosterList["ITO1_1999-01-01"].shiftList).length);
    console.log(Object.keys(rosterList.present["ITO1_1999-01-01"].shiftList).length);
    //console.log(contextValue);
    return (
        <table>              
        </table>
    )
}

我正在使用use-undo包来实现撤消功能。

我使用 useUndo 挂钩将父提供的数据(即props.rosterTableData.rosterList)转换为撤消变量rosterList

问题:

我发现rosterList更新内容时,内容不会props.rosterTableData.rosterList更新。

我试过的:

我试图将代码修改为以下内容:

import useUndo from 'use-undo';
export default function UndoTable(props){
    const [hightLightCellIndex, setHightLightCellIndex] = useState(-1);
    let [
        rosterList,
        undoUtil
    ]=useUndo(props.rosterTableData.rosterList);
        
    useEffect(()=>{
        console.log(Object.keys(props.rosterTableData.rosterList["ITO1_1999-01-01"].shiftList).length);
        console.log(Object.keys(rosterList.present["ITO1_1999-01-01"].shiftList).length);
        },[props.rosterTableData])
    //console.log(contextValue);
        
    return (
        <table>              
        </table>
    )
}

不幸的是,问题仍然存在。有没有办法解决这个问题?

标签: javascriptreactjs

解决方案


您似乎使用useUndo不正确。查看文档

您传递给useUndo函数的是initialState,因此如果您传递不同的值,它将不会更新。如果你想重置撤销状态,你应该调用 reset 方法:

useEffect(() => {
    undoUtil.reset(props.rosterTableData.rosterList)
}, [props.rosterTableData.rosterList])

推荐阅读