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

我想对你说

React的useCallback没起作用,是怎么回事?加了依赖项sortRuleList了,而sortRuleList在newsortRule函数里先行调用了,没啥问题啊,为什么打印出来还是空? ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240926/65e35821d8c1d9a5aa098a3d7b85d31f.png) const [sortRuleList, setSortRuleList] = useState([]) 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 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240926/a3110c87ef5f1433e566abcc6e2d4ad0.png)

阅读量:210

点赞量:0

问AI
const [sortRuleList, setSortRuleList] = useState([]); 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]);