React的useCallback没有按预期工作,依赖项sortRuleList未更新,问题出在哪里?

React的useCallback没起作用,是怎么回事?加了依赖项sortRuleList了,而sortRuleList在newsortRule函数里先行调用了,没啥问题啊,为什么打印出来还是空?

    const [sortRuleList, setSortRuleList] = useState<any>([])
    const newsortRule = ()=>{
        const arr = [...sortRuleList]
        arr.push({
            sortTypeCode:'',
            sortType:'',
            orderType:''
        })
        setTimeout(()=>{
            setSortRuleList(arr)
            ref.current.reload()
        },0)
    }
    const onCellChange = useCallback((value: any, type:any, idx: any) => {
        console.log("888888",sortRuleList)  //为什么打印出来是空
            const arr = [...sortRuleList]  //为什么打印出来是空
            console.log("99999",arr)
            if(type == 'sortTypeCode'){
                arr[idx]['sortTypeCode'] = value
                sortbyArr.forEach((ele) => {
                    if (ele.value == value) {
                        arr[idx]['sortType'] = ele.label
                    }
                })
            }
            if(type == 'orderType'){
                arr[idx]['orderType'] = value
            }
            setSortRuleList(arr)
    },[sortRuleList])

自己一直在调试,没成功。
再问楼下回答的大佬,没成功,打印出来,909090 undefined

阅读 581
1 个回答
const [sortRuleList, setSortRuleList] = useState<any>([]);

const newsortRule = () => {
    setSortRuleList(prevList => {
        const newList = [...prevList, { sortTypeCode: '', sortType: '', orderType: '' }];
        setTimeout(() => {
            console.log("Updated sortRuleList:", newList);
            ref.current.reload();
        }, 0);
        return newList;
    });
};

const onCellChange = useCallback((value: any, type: any, idx: any) => {
    setSortRuleList(prevList => {
        const newList = [...prevList];
        if (type === 'sortTypeCode') {
            newList[idx]['sortTypeCode'] = value;
            sortbyArr.forEach(ele => {
                if (ele.value == value) {
                    newList[idx]['sortType'] = ele.label;
                }
            });
        }
        if (type === 'orderType') {
            newList[idx]['orderType'] = value;
        }
        return newList;
    });

    setTimeout(() => {
        // 这里用最新 sortRuleList 值
        setSortRuleList(prevList => {
            console.log("909090", prevList);
            return prevList; // 日志
        });
    }, 0);
}, [sortbyArr]);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏