首页 > 解决方案 > 未使用 redux 验证条件时如何防止重新渲染页面

问题描述

我有一个页面,其中包含一篇论文,其中包含一个问题和一个选项列表以及一个重定向到下一个问题的按钮。

import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import React, { useEffect } 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 { Field, reduxForm } from "redux-form";
import { 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: () => void;
  numberOfQuestions: number;
}

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

  const handleNextQuiz = () => {
    if (currentQuestionNumber === numberOfQuestions - 1) {
      history.push("/homepage");
    }
    incrementQuestion();
    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}>
                        <Field
                          name={fieldName}
                          component={CheckBoxWrapper}
                          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: () => dispatch<any>(incrementQuestion()),
    questionRequest: () => dispatch<any>(questionRequest())
  };
};

const QuizContainer = reduxForm<{}, IProps>({
  form: "Answers",
  destroyOnUnmount: false,
})(Quiz);

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

handleNextQuiz增加问题编号的计数器并重定向到同一页面以重新呈现组件(我认为在每次单击按钮时重定向到相同的页面并不是最好的主意,并且欢迎任何处理该问题的建议)。但我想检查何时应该将用户重定向到另一个页面以验证和提交的最后一个问题。但是,对于我的代码,当使用问题列表测试组件以及尝试将用户重定向到最终页面时。组件重新渲染并发生错误提及:

TypeError: Cannot read property 'description' of undefined

我该如何处理这种情况,以便在最后一个问题中单击下一步按钮时不重新呈现同一页面。

标签: javascriptreactjsredux

解决方案


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

上述函数不正确,假设满足第一个条件,成功重定向到/homepage,函数还没有结束。incrementQuestion();被执行,然后重定向到/contentQuiz.

您需要return在 if 条件中添加一条语句以避免执行后面的代码,或者使用if else. 所以基本上,一次应该只有 1 个重定向。

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

推荐阅读