React 有条件地渲染 div

React conditionally render a div

我正在尝试向我的测验应用程序添加一个提示选项。 如果单击 50/50 按钮,我想呈现 newAnswers 数组。否则我想渲染 shuffledAnswers 数组。

当我 运行 我得到这个代码时

TypeError: Cannot read properties of null (reading 'useState')

我做错了什么?

import React from "react";
import { useState } from "react/cjs/react.production.min";
import Card from "../UI/Card";
import "./DisplayQuestion.css";
import ProgressBar from "./Progress";

const DisplayQuestion = (props) => {
  /*I used dangerouslySetInnerHTML to fix the quotes gibberish problem */
  const [hint, setHint] = useState(false);
  console.log("hint: ", hint);
  let notBoolean = false;
  const newAnswers = [
    props.data.correct_answer,
    props.data.incorrect_answers[0],
  ];

  /*Helper functions */

  // shuffles the answers
  let shuffledAnswers = [
    props.data.correct_answer,
    ...props.data.incorrect_answers,
  ].sort(() => Math.random() - 0.5);

  if (shuffledAnswers.length > 2) {
    notBoolean = true;
    console.log("notBoolean");
  }
  const answersHintHandler = () => {
    setHint(true);
    console.log("hint: ", hint);
    console.log(newAnswers);
  };

  let progress = Math.round((props.score / props.numOfQuestions) * 100);

  return (
    <div>
      <h3 class="diff">Difficulty: {props.diff}</h3>
      <div classname="Questions">
        <Card>
          <ProgressBar bgcolor="#99ccff" progress={progress} height={30} />
          <h2>
            Questions {props.index}/{props.numOfQuestions}
          </h2>

          <h2
            className="question-text"
            dangerouslySetInnerHTML={{
              __html: props.data.question,
            }}
          />

          <ul>
            {notBoolean ? (
              <button onClick={answersHintHandler}>50/50</button>
            ) : (
              <p></p>
            )}
            {hint
              ? newAnswers.map((answer) => {
                  return (
                    <li
                      onClick={() => props.handler(answer)}
                      dangerouslySetInnerHTML={{
                        __html: answer,
                      }}
                    ></li>
                  );
                })
              : shuffledAnswers.map((answer) => {
                  return (
                    <li
                      onClick={() => props.handler(answer)}
                      dangerouslySetInnerHTML={{
                        __html: answer,
                      }}
                    ></li>
                  );
                })}
          </ul>
        </Card>
      </div>
    </div>
  );
};

导出默认显示问题;

您正在从错误的路径导入 useState x)

import { useState } from "react/cjs/react.production.min";

关心自动导入哈哈

将第一行和第二行替换为

import React, { useState } from 'react'