React Ionic hooks组件设置值不起作用



我制作了一个组件,它有一个从Ionic/Rect中选择的选项,其中我有一个名为licenseValue的对象。然而,当我尝试setLicenseValue时,如果我尝试console;值";,它不会更新值。

import licenseValuesArray from './somewhere'
const [licenseValues, setLicenseValues] = useState(licenseValuesArray);
useEffect(() => {
setLicenseValues(licenseValuesArray);
}, [licenseValuesArray]);
const [licenseValue, setLicenseValue] = useState(0);
<IonSelect
value="value"
okText="Okay"
cancelText="Dismiss"
onIonChange={(e) => {
e.preventDefault();
let a = e.detail.value;
setLicenseValue(a);
console.log(a, "defina periodo");//retrieve the "a" value
console.log(licenseValue, "defina periodo");//doesnt retrieve the value from setLicenseValue
}}
>
{licenseValues.map((item) => (
<IonSelectOption key={item.title} value={item}>
{item.title}
</IonSelectOption>
))}
</IonSelect>

我正在使用React/Ionial/hooks

您需要记住,在React状态下,更新可能是异步的。特别是,useState挂钩在下一个渲染周期之前不会为licenseValue提供更新的值。因此,您发布的示例代码将记录以前的值。

如果console.log已经更改或没有更改,最好的日志方式是将CCD_7移动到每次licenseValue更改时执行的useEffect挂钩,从而为您提供当前值。

useEffect(() => {
console.log(licenseValue);
}, [licenseValue]);

相关内容

最新更新