重新渲染组件时如何使用react hook重新初始化状态

时间:2019-10-04 13:59:35

标签: javascript reactjs redux

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

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);

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

2 个答案:

答案 0 :(得分:1)

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

在转到下一个问题时重置fieldName

答案 1 :(得分:1)

我认为您只需要修复useEffect

  useEffect(() => {
    setAnswerOption({
      option1: false,
      option2: false,
      option3: false,
      option4: false,
    });

    questionRequest();
  }, []);

此外,不要忘记传递第二个参数,否则您的组件中可能存在无限循环。 https://reactjs.org/docs/hooks-effect.html