【问题标题】:React Ionic hooks Component setValue isnt workingReact Ionic hooks 组件 setValue 不起作用
【发布时间】:2021-04-15 02:29:10
【问题描述】:

我制作了一个组件,该组件具有来自 Ionic/React 的选择选项,其中我有一个名为 licenseValue 的对象。但是,当我尝试setLicenseValue 时,如果我尝试console licenseValue“值”,它不会更新该值。

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 / Ionic / hooks

【问题讨论】:

    标签: reactjs ionic-framework react-hooks


    【解决方案1】:

    您需要记住,在 React state updates may be asynchronous 中。特别是,useState 挂钩在下一个渲染周期之前不会为您提供 licenseValue 的更新值。因此,您发布的示例代码将记录以前的值。

    记录是否已更改的更好方法是将您的 console.log 移动到每次 licenseValue 更改时执行的 useEffect 挂钩,为您提供当前值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      相关资源
      最近更新 更多