简体   繁体   中英

using prop value in useState hook gives undefined value

Have a React Component that sets a state using hooks from props.
prop is storedStep. prop value is used to setState in a hook.

But state is set to undefined, even if console.log says prop has a number value

line 41     console.log(storedStep)
      const [activeStep, setActiveStep] = React.useState(1);
      const [activeStep2, setActiveStep2] = React.useState(storedStep);
line 44      console.log(activeStep)
line 45       console.log(activeStep2)

在此处输入图像描述

This is for a material ui stepper https://material-ui.com/components/steppers/

I am setting the active step of a Stepper https://codesandbox.io/s/qhhv1?file=/demo.js The example in the demo for the stepper does not use a prop to set the active Step, but sets it to 0.

Where storedStep is defined.

It's defined in the direct parent component.

I use another hook in direct parent

const [projDetail, setProjDetail] = useState({});

and pass the setProjDetail function in the useEffect of this parent

 useEffect(() => {
    async function fetchData() {
      await getDetailFunc (email, projectid, setProjDetail);
    }

    fetchData();
  }, [email, projectid,getDetailFunc]);

getDetailFunc will fetch the detail and set the projDetail using setProjDetail

storedState is a property of projDetail which is passed to the child

storedStep={projDetail.requeststatus}

storedStep is correctly getting the value 0 at some point(line 41). But not able to set it to the activeStep(line 45)

I fixed this in my case by rendering the child component in parent only after checking for existence of the attribute "requeststatus"

if (projDetail.hasOwnProperty("requeststatus")) {

.....
...
    <Stepper
      steps={steps}
      storedStep={projDetail.requeststatus}
      saveStageFunc={saveStageinDynamo}
      updateKey={{ email, projectid }}
      labelArray={processStates}
    />

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM