[英]React Native - React Hooks - useState is not updating my state immediately
I am trying to pass the updated value through convert function to display the new result on every state update but it seems the states "const [values]" is not updating immediately and I am getting results from previous state value.我试图通过 convert function 传递更新的值,以在每次 state 更新时显示新结果,但似乎状态“const [values]”没有立即更新,我正在从以前的 state 值中获取结果。 So with every value change my results are a step behind.
因此,随着每一次价值变化,我的结果都落后了一步。 In the console I can see I am getting new value from the input but the "values" state shows previous values.
在控制台中,我可以看到我从输入中获取了新值,但“值”state 显示了以前的值。
const [values, setValues] = useState({ sqmtr: "", sqft: "", }); const handleTextChange = (text, name) => { setValues({...values, [name]: text }); convert(unit, values); console.log(text); console.log(values); };
<TextInput style={styles.inputField} defaultValue={values.sqmtr} onChangeText={(text) => handleTextChange(text, "sqmtr")} placeholder="0" keyboardType={"numeric"} />
It works fine, because setState
is asynchronous.它工作正常,因为
setState
是异步的。 New set value will be seen in a new component render.新的设置值将在新的组件渲染中看到。
const handleTextChange = (text, name) => {
const value = { ...values, [name]: text }
// `setValues` is async. so use the value directly
setValues(value);
convert(unit, value);
console.log(text);
console.log(values);
};
Use async/await before logging the result在记录结果之前使用 async/await
const handleTextChange = async(text, name) => {
await setValues({ ...values, [name]: text });
await convert(unit, values);
await console.log(text);
await console.log(values);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.