javascript - 重新渲染组件时如何使用 react 钩子(Hook)重新初始化状态

标签 javascript reactjs redux

我创建了一个组件来显示问题及其不同选项,当用户单击下一步按钮时,将执行到同一页面的重定向以重新呈现组件并显示新问题。 我使用复选框组件来显示问题选项,但每当我选择一个选项并转到下一个问题时;复选框不会为新的复选框重置(例如,如果我为第一个问题选中了第二个选项,那么在我选中它之前,我在第二个问题中选中了第二个选项)。

import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import SyntaxHighlighter from "react-syntax-highlighter";
import { dark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { Dispatch } from "redux";
import { IAnswer, incrementQuestion, IQuestion, questionRequest } from "../../actions/index";
import CheckBoxWrapper from "../../components/common/CheckBoxWrapper";
import ContentQuiz from "../../components/ContentQuiz";
import history from "../../history/history";

interface IProps {
  currentQuestionNumber: number;
  loadingData: boolean;
  questions: IQuestion[];
  questionRequest: () => void;
  incrementQuestion: (arg: IAnswer) => void;
  numberOfQuestions: number;
}

interface IAnswerOption {
  option1: boolean;
  option2: boolean;
  option3: boolean;
  option4: boolean;
  [key: string]: boolean;

}

const Quiz = (props: IProps) => {
  const { currentQuestionNumber,
    loadingData,
    questions,
    questionRequest,
    incrementQuestion,
    numberOfQuestions } = props;

  const [answerOption, setAnswerOption] = useState<IAnswerOption>({
    option1: false,
    option2: false,
    option3: false,
    option4: false,
  });

  const handleChange = (option: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setAnswerOption({ ...answerOption, [option]: event.target.checked });
  };
  useEffect(() => {
    questionRequest();
  });

  const handleNextQuiz = () => {
    if (currentQuestionNumber === numberOfQuestions - 1) {
      history.push("/homepage");
    } else {
      incrementQuestion(answerOption);
      history.push("/contentQuiz");
    }

  };

  const currentQuestion = questions[currentQuestionNumber];
  return (
    <div>
      {loadingData ? ("Loading ...") : (
        < ContentQuiz
          questionNumber={currentQuestionNumber + 1}
          handleClick={handleNextQuiz} >
          <div>
            <Typography variant="h3" gutterBottom> What's the output of </Typography>
            <>
              <SyntaxHighlighter language="javascript" style={dark} >
                {currentQuestion.description.replace(";", "\n")}
              </SyntaxHighlighter >
              <form>
                <Grid container direction="column" alignItems="baseline">
                  {currentQuestion.options.map((option: string, index: number) => {
                    const fieldName = `option${index + 1}`;
                    return (
                      <Grid key={index}>
                        <CheckBoxWrapper
                          checked={answerOption[fieldName]}
                          value={fieldName}
                          onChange={handleChange(fieldName)}
                          label={option}
                        />
                      </Grid>);
                  }
                  )}
                </Grid>
              </form>
            </>
          </div >
        </ContentQuiz >
      )}
    </div>
  );
};

const mapStateToProps = (state: any) => {
  const { currentQuestionNumber, loadingData, questions, numberOfQuestions } = state.quiz;

  return {
    currentQuestionNumber,
    loadingData,
    questions,
    numberOfQuestions
  };
};

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    incrementQuestion: (answer: IAnswer) => dispatch<any>(incrementQuestion(answer)),
    questionRequest: () => dispatch<any>(questionRequest())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Quiz);

如何在重新渲染组件时重置问题选项,以便检查选项?

最佳答案

 const fieldName = `option${index + 1}`;

在进入下一个问题时重置 fieldName

关于javascript - 重新渲染组件时如何使用 react 钩子(Hook)重新初始化状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237895/

相关文章:

reactjs - 如何在 react 中增加和减少状态值?

javascript - 使用ngrx效果时避免多次请求

javascript - 参数未传递给 ng-submit 上的函数

javascript - 如何显示来自 JSON 的视频?

javascript - 如何使用 jQuery 数据表使用 onChange 事件从 html 选择标签选项值中获取值?

javascript 打印 tofixed 如果不可能则打印正常

reactjs - 满足最少条件时如何使用 yup 验证密码

node.js - 服务器端渲染中的 ComponentDidMount()

javascript - 扩展 Immutable 中的属性

javascript - 在 React/Redux 中创建新项目并稍后保存到服务器