reactjs React是忘记选择多步表上的值

798qvoo8  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(111)

所以我遇到了一个问题。我使用react-form-hook和material-ui来创建多步骤表单。问题是当我向前stem react-form-hook时忘记了select值。select组件:

const Second_step_component = ({ register, errors }) => {
    const [age, setAge] = React.useState('');
    

    const handleChange = (event) => {
        setAge(event.target.value);
    };

    return (
        <FormControl sx={{ m: 1, minWidth: 120 }} error={Boolean(errors.Age)}>
            <InputLabel id="demo-simple-select-helper-label">Age</InputLabel>
            
            <Select
                labelId="demo-simple-select-helper-label"
                id="demo-simple-select-helper"
                value={age}
                label="Age"
                {...register("Age", {required: "Age Is Required"})}
                onChange={handleChange}
            >

                <MenuItem value={10}>Ten</MenuItem>
                <MenuItem value={20}>Twenty</MenuItem>
                <MenuItem value={30}>Thirty</MenuItem>
            </Select>
            <FormHelperText>{errors.Age?.message}</FormHelperText>
        </FormControl>
    );
}
export default Second_step_component

我知道它会恢复到默认状态"“,但是当我的知识似乎仅限于将useState更改为register(“Age”)时,如果有人能给予我一些提示,我将非常感激
还包括步进主部件:

const steps = ['House', 'Materials'];

export default function HorizontalLinearStepper() {
  const [activeStep, setActiveStep] = React.useState(0);
  const [skipped, setSkipped] = React.useState(new Set());
  const {register, handleSubmit, formState: {errors}, trigger} = useForm()
  const [state, setstate] = useState([{}]);

  const isStepOptional = (step) => {
    return step === 1;
  };

  const isStepSkipped = (step) => {
    return skipped.has(step);
  };

  const handlesub = (data) =>{
    setstate(data)
    console.log(data)
  }
  const handleNext = async (e) => {
    e.preventDefault()
    let isNext = false
    
    switch(activeStep){
      case 0: isNext = await trigger(["Miestas", "Getvė", "Numeris"]);
      break;
      case 1: isNext = await trigger(["Age"]);
      break;
    }
    if(isNext){
      setActiveStep((prevActiveStep) => prevActiveStep + 1);
    }

  };

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  const handleSkip = () => {
    if (!isStepOptional(activeStep)) {
      // You probably want to guard against something like this,
      // it should never occur unless someone's actively trying to break something.
      throw new Error("You can't skip a step that isn't optional.");
    }

    setActiveStep((prevActiveStep) => prevActiveStep + 1);
    setSkipped((prevSkipped) => {
      const newSkipped = new Set(prevSkipped.values());
      newSkipped.add(activeStep);
      return newSkipped;
    });
  };

  let Swithing = null
  switch (activeStep) {
    case 0:
      Swithing = <First_step_component register={register} errors={errors}/>
      break

    case 1:
      Swithing = <Second_step_component register={register} errors={errors}/>
      break
    
  }

  const handleReset = () => {
    setActiveStep(0);
  };

  return (
    <Box sx={{padding: "2rem", display: "grid", placeContent: "center"}}>
    <Box sx={{ width: '500px' }}>
      <Stepper activeStep={activeStep}>
        {steps.map((label, index) => {
          const stepProps = {};
          const labelProps = {};
          if (isStepOptional(index)) {
            labelProps.optional = (
              <Typography variant="caption">Optional</Typography>
            );
          }
          if (isStepSkipped(index)) {
            stepProps.completed = false;
          }
          return (
            <Step key={label} {...stepProps}>
              <StepLabel {...labelProps}>{label}</StepLabel>
            </Step>
          );
        })}
      </Stepper>
      {activeStep === steps.length ? (
        <React.Fragment>
          <Typography sx={{ mt: 2, mb: 1 }}>
            All steps completed - you&apos;re finished
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Box sx={{ flex: '1 1 auto' }} />
            <Button onClick={handleReset}>Reset</Button>
          </Box>
        </React.Fragment>
      ) : (
        <React.Fragment>

       
          <Typography sx={{ mt: 2, mb: 1 }}>Step {activeStep + 1}</Typography>
          <form id='step-form-sub' onSubmit={handleSubmit(handlesub)}>
            <Box>{Swithing}</Box>
          </form>
          
          

          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Button
              color="inherit"
              disabled={activeStep === 0}
              onClick={handleBack}
              sx={{ mr: 1 }}
            >
              Back
            </Button>
            <Box sx={{ flex: '1 1 auto' }} />
            {/* {isStepOptional(activeStep) && (
              <Button color="inherit" onClick={handleSkip} sx={{ mr: 1 }}>
                Skip
              </Button>
            )} */}

            {activeStep === steps.length - 1?
            (<Button form="step-form-sub" type='submit'>submit</Button>)
            :
            (<Button type='button' onClick={handleNext}>next</Button>)
            }

            
          </Box>
        </React.Fragment>
      )}
    </Box>
    </Box>
  );
}
hjqgdpho

hjqgdpho1#

这是因为你设计stepper的方式。
卸载后,第二步中的状态将恢复为原始值。
解决方案是将状态移动到 Package 器组件中(例如,如果您的 Package 器组件是App.jsx =〉,则将所有步进器状态移动到其中)
请看下面代码笔上的步进器来了解:
React stepper

const App = () => {
    const [acceptFirstTerms, setAcceptFirstTerms] = useState({
            checked: false,
            touched: false,
        }),
        [acceptSecondTerms, setAcceptSecondTerms] = useState({
            checked: false,
            touched: false,
        }),
        [acceptThirdTerms, setAcceptThirdTerms] = useState({
            checked: false,
            touched: false,
        }),
        [isSecondStepLoading, setIsSecondStepLoading] = useState(false);

    const firstTermsHandler = () => {
        setAcceptFirstTerms((prev) => ({ checked: !prev.checked, touched: true }));
    };

    const secondTermsHandler = () => {
        setAcceptSecondTerms((prev) => ({ checked: !prev.checked, touched: true }));
    };

    const thirdTermsHandler = () => {
        setAcceptThirdTerms((prev) => ({ checked: !prev.checked, touched: true }));
    };

    //for demo purposes only
    const timeout = (ms) => {
        return new Promise((resolve) => setTimeout(resolve, ms));
    };

    const secondStepAsyncFunc = async () => {
        //it can be an API call
        setIsSecondStepLoading(true);
        await timeout(3000);
        setIsSecondStepLoading(false);
        console.log('second step clicked');
    };

    const stepperContent = [
        {
            label: 'Step 1',
            content: (
                <div>
                    <label>
                        <input
                            type="checkbox"
                            checked={acceptFirstTerms.checked}
                            onChange={firstTermsHandler}
                        />{' '}
                        Accept first terms and conditions
                    </label>
                </div>
            ),
            isError: !acceptFirstTerms.checked && acceptFirstTerms.touched,
            isComplete: acceptFirstTerms.checked,
        },
        {
            label: 'Step 2',
            content: (
                <div>
                    <label>
                        <input
                            type="checkbox"
                            checked={acceptSecondTerms.checked}
                            onChange={secondTermsHandler}
                        />{' '}
                        Accept second terms and conditions
                    </label>
                </div>
            ),
            clicked: () => secondStepAsyncFunc(),
            isLoading: isSecondStepLoading,
            isError: !acceptSecondTerms.checked && acceptSecondTerms.touched,
            isComplete: acceptSecondTerms.checked,
        },
        {
            label: 'Step 3',
            content: (
                <div>
                    <label>
                        <input
                            type="checkbox"
                            checked={acceptThirdTerms.checked}
                            onChange={thirdTermsHandler}
                        />{' '}
                        Accept third terms and conditions
                    </label>
                </div>
            ),
            isError: !acceptThirdTerms.checked && acceptThirdTerms.touched,
            isComplete: acceptThirdTerms.checked,
        },
    ];

    const submitStepper = () => {
        console.log('submitted');
    };

    return (
        <div className="container">
            <h2>Default stepper</h2>
            <Stepper stepperContent={stepperContent} submitStepper={submitStepper} />
            <hr />
            <h2>Inline stepper</h2>
            <Stepper stepperContent={stepperContent} submitStepper={submitStepper} isInline />
            <hr />
            <h2>Vertical stepper</h2>
            <Stepper stepperContent={stepperContent} submitStepper={submitStepper} isVertical />
        </div>
    );
};

相关问题