简体   繁体   English

反应幻灯片动画删除 unmountOnExit 上的选定值

[英]React Slide Animation removing selected value on unmountOnExit

I am facing a issue, on click of radio button the next question comes using slide animation, But on unmounting on Exit the previously selected radio button value is also getting deselected.我遇到了一个问题,单击单选按钮时,下一个问题使用幻灯片动画,但在退出时卸载先前选择的单选按钮值也被取消选择。 How to prevent this from happening.如何防止这种情况发生。

const Quiz = (props) => {
     const {questions, quiz, options} = useSelector((state) => state.quiz);
  
    const [user, setuser] = useState("");
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [checked, setChecked] = useState(true);  
    const [option, setOptions] = useState("");
    
    const dispatch = useDispatch();
    const history = useHistory();

 const handleRadioChange = (number, event) => {
  
    let currentSelection = questions.find(question => question.number === number);
    console.log(currentSelection + "radio selected");
    currentSelection.value = event.target.value;
  
    questions[currentQuestion].value = event.target.value;
   
    console.log(questions[currentQuestion].value + "value added");
    setCurrentQuestion((current) => {
      return Math.min(
        current + 1,
        questions.length - 1
      );
    });
      setChecked((previousState) => !previousState);
      setTimeout(() => { 
        setChecked(previousState => ({
             afterPreviousChange: previousState.previousChange 
           }))
      }, 1000);
    
};


    const previousQuestion = (event) => {
        event.preventDefault();
        let new_current_questions = Math.max(currentQuestion - 1, 0);
        setCurrentQuestion(new_current_questions);
        setChecked((previousState) => !!previousState);
       const a =  setTimeout(() => { 
          setChecked(previousState => ({
               afterPreviousChange: previousState.previousChange 
             
             }))
        }, 1000);
       
      };
 function handleSubmit(event) {
        event.preventDefault();     
        const valid = questions.some((q) => !q.value);
        console.log(valid + "questionsalpha");
        if (!valid) {
            dispatch(postQuiz({ responses: questions, id: quiz.id }, history));
        }
        setChecked((previousState) => !previousState);
        const a =  setTimeout(() => {                
            setChecked((previousState) => !previousState);   
            setCurrentQuestion(0);
              },1000);};
    return(

      <Slide direction="up"  
        in={checked} 
        appear={true} 
        mountOnEnter 
                 unmountOnExit
        timeout={{ enter: 1000 , exit: checked ? 1 : 900}}
    >   
            <Card variant="outlined" sx={{ bgcolor: "#bea"}} elevation={0}>
                <CardContent>
    
                <form onSubmit= {handleSubmit}>
                        <CardActions>
                      <Button type="submit" color="warning" variant="outlined" disabled={currentQuestion===0} className={classes.button} onClick={previousQuestion}>
                          Previous</Button>
                      </CardActions>              
                      <FormControl component='fieldset' className={classes.formControl}
        data-hidden={questions[currentQuestion].number !==
          currentQuestion[questions[currentQuestion].number]} >
        <FormLabel component='legend'>
          {questions[currentQuestion].question}
        </FormLabel>
        <FormLabel component='legend'>
          {questions[currentQuestion].description}
        </FormLabel>
        <RadioGroup
          aria-label='quiz'
          name='quiz'
          defaultValue={' '}
          value={questions[currentQuestion].value}
          checked={checked}
          onChange={(e)=> handleRadioChange(questions[currentQuestion].number, e)}
          sx={{
            color: pink[800],
            '&.Mui-checked': {
              color: blue[600],
            },
          }}>
          {options.map((option) => (
            <FormControlLabel
              key={option.score}
              value={option.score}
              control={<Radio  sx={{
                color: pink[800],
                '&.Mui-checked': {
                  color: blue[600],
                },
              }}/>}
              label={option.label}
             
            />
          ))}
        </RadioGroup>
      </FormControl>
                        <CardActions>
                        <Button type="submit" variant="contained" color="primary" className={classes.button} disabled={currentQuestion<5} onClick={handleSubmit}>
                        Submit
                    </Button>
                  </CardActions>
                    </form>
                    </CardContent>
                    </Card>
                    </Slide>
      );

function using handleChange and previous button is also I have shared.我也分享了使用 handleChange 和上一个按钮的功能。 Please help with this issue.请帮助解决这个问题。

The main reason for previously radio button value not persist is because you are not changing the questions state with the update values, you are just changing the object itself.以前单选按钮值不存在的主要原因是因为您没有使用更新值更改questions状态,您只是更改了对象本身。

The error is specifically here:错误具体在这里:

let currentSelection = questions.find(question => question.number === number);

console.log(currentSelection + "radio selected");

// HERE YOU ARE CHANGIG ONLY THE OBJECT, NOT THE ARRAY
currentSelection.value = event.target.value;
  
questions[currentQuestion].value = event.target.value;

One way to do this is map the questions array, change the current question value and then update the questions state:一种方法是映射问题数组,更改当前问题值,然后更新问题状态:

const updatedQuestions = questions.map((item) => {
   if (item.number === currentQuestion) item.value = event.target.value;
      return item;
   });

setQuestions(updatedQuestions);

But your code also have other inconsistencies, i did a code sample for you with comments.但是您的代码也有其他不一致之处,我为您做了一个带有注释的代码示例

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

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