reactjs - 如何在反应钩子中的状态更改后立即获取状态
问题描述
大家好,设置状态后我无法获得当前状态。我正在调用一个函数,我正在传递该状态,但我总是在该函数中获得默认状态。这是我的状态-
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 函数中获得更新状态。但是是的,如果我试图在渲染中控制状态,那么它会向我显示更新的状态,但在功能上它不会更新。如何在这两个函数中实现更新状态?
解决方案
如果我正确地回答了您的问题,那么这可能会有所帮助:
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
推荐阅读
- python - 无法在 Windows 上的 VScode 3.8.5 中安装 pyaudio
- python - 熊猫传递参数以申请
- c++ - 在命名空间内的变量之前“使用”
- sql - SQL:嵌套子查询错误地返回条目
- python - 创建衡量 F1 损失的标准
- javascript - 为 MERN 开发 Javscript OOP 项目:类和构造函数
- node.js - 对于这些对象的有效排序/嵌套算法有什么想法吗?
- reactjs - React 测试库 - 使用 FileReader 模拟上传文件
- javascript - 获取“主”域名JS
- ios - addSubview 和 addArrangedSubview 不显示内容