简体   繁体   English

在 useState 钩子中使用 prop 值会给出未定义的值

[英]using prop value in useState hook gives undefined value

Have a React Component that sets a state using hooks from props.有一个 React 组件,它使用 props 中的钩子设置 state。
prop is storedStep.道具存储步骤。 prop value is used to setState in a hook. prop 值用于在挂钩中设置状态。

But state is set to undefined, even if console.log says prop has a number value但是 state 设置为 undefined,即使 console.log 说 prop 有一个数值

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/这是用于材料ui步进器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.我正在设置 Stepper https://codesandbox.io/s/qhhv1?file=/demo.js步进器的活动步骤 步进器演示中的示例不使用道具来设置活动步骤,而是将其设置为0。

Where storedStep is defined.定义了 storedStep 的位置。

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 中传递 setProjDetail function

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

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

getDetailFunc will fetch the detail and set the projDetail using setProjDetail getDetailFunc 将获取详细信息并使用 setProjDetail 设置 projDetail

storedState is a property of projDetail which is passed to the child storedState 是传递给子进程的 projDetail 的属性

storedStep={projDetail.requeststatus}

storedStep is correctly getting the value 0 at some point(line 41). storedStep 在某个点(第 41 行)正确获取值 0。 But not able to set it to the activeStep(line 45)但无法将其设置为 activeStep(第 45 行)

I fixed this in my case by rendering the child component in parent only after checking for existence of the attribute "requeststatus"在我的情况下,我通过仅在检查属性“requeststatus”是否存在后才在父组件中渲染子组件来解决此问题

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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