首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在重登组件时使用react钩子重新初始化状态

如何在重登组件时使用react钩子重新初始化状态
EN

Stack Overflow用户
提问于 2019-10-04 13:59:35
回答 2查看 724关注 0票数 1

我创建了一个组件来消除一个问题及其不同的选项,当用户单击next按钮时,将执行对同一个页面的重定向,以便重新修改组件并显示一个新的问题。我使用一个checkBox组件来显示问题选项,但是每当我选择一个选项并进入下一个问题时,都不会为新的选项重置复选框(例如,如果我选中了第一个问题的第二个选项,那么在选中第二个问题之前,第二个选项就会被选中)。

代码语言:javascript
复制
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);

当我重新复制组件时,我如何重新设置问题选项,以检查选项?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-04 15:34:02

代码语言:javascript
复制
 const fieldName = `option${index + 1}`;

当你要问下一个问题时,重置fieldName

票数 1
EN

Stack Overflow用户

发布于 2019-10-04 17:17:59

我认为你只需要修复你的useEffect

代码语言:javascript
复制
  useEffect(() => {
    setAnswerOption({
      option1: false,
      option2: false,
      option3: false,
      option4: false,
    });

    questionRequest();
  }, []);

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58237895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档