首页 > 解决方案 > 如何在反应钩子中的状态更改后立即获取状态

问题描述

大家好,设置状态后我无法获得当前状态。我正在调用一个函数,我正在传递该状态,但我总是在该函数中获得默认状态。这是我的状态-

const [currentValue , setCurrentValue] = useState(one[0]); // where one[0] is string "Test"

这是我的 onchange 功能-

const getTest = useCallback((newValue:string) => {
 setCurrentValue({
    label:newValue,
    value:newValue
});
  getCurrentValue(currentValue.value);
  getSortOrder()
}, [])

这是我的 getSortOrder 函数 -

const getSortOrder  =() => {
console.log(currentValue);
}

我没有在 getSortOrder 函数和 getCurrentValue 函数中获得更新状态。但是是的,如果我试图在渲染中控制状态,那么它会向我显示更新的状态,但在功能上它不会更新。如何在这两个函数中实现更新状态?

标签: reactjstypescript

解决方案


如果我正确地回答了您的问题,那么这可能会有所帮助:

const getTest = useCallback((newValue:string) => {
 setCurrentValue({
    label:newValue,
    value:newValue
});
//try this code doing in useEffect
}, [])       

 useEffect(() => {
           getCurrentValue(currentValue.value);
           getSortOrder()
      },[currentValue]); //Everytime currentValue changes it will give new state

推荐阅读