Anu*_*hra 5 typescript reactjs
大家好,我在设置状态后无法获取当前状态。我正在调用一个函数,我在其中传递该状态,但我总是在该函数中获得默认状态。这是我的状态-
const [currentValue , setCurrentValue] = useState(one[0]); // where one[0] is string "Test"
Run Code Online (Sandbox Code Playgroud)
这是我的 onchange 函数 -
const getTest = useCallback((newValue:string) => {
setCurrentValue({
label:newValue,
value:newValue
});
getCurrentValue(currentValue.value);
getSortOrder()
}, [])
Run Code Online (Sandbox Code Playgroud)
这是我的 getSortOrder 函数 -
const getSortOrder =() => {
console.log(currentValue);
}
Run Code Online (Sandbox Code Playgroud)
我没有在 getSortOrder 函数和 getCurrentValue 函数中获取更新的状态。但是,是的,如果我试图在渲染中控制台状态,那么它会向我显示更新的状态,但在功能中它不会更新。如何在两个函数中实现更新状态?
小智 1
如果我正确地理解了你的问题,那么这可能会有所帮助:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2664 次 |
| 最近记录: |