Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

reactjs - React Ionic hooks Component setValue isnt working

I've made a component that has a select option from Ionic/React where I have an object called licenseValue. However, when I try to setLicenseValue, if I try to console the licenseValue "value", it doesn't update the value.

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>

I'm using React / Ionic / hooks

question from:https://stackoverflow.com/questions/65644969/react-ionic-hooks-component-setvalue-isnt-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'll want to keep in mind that in React state updates may be asynchronous. In particular, the useState hook is not going to give you an updated value for licenseValue until the next render cycle. So the sample code you posted will aways log the previous value.

A better way log if it has changed or not would be to move your console.log to a useEffect hook that executes each time licenseValue changes, giving you the current value.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...