开发者问题收集

类型错误:无法读取 undefined1 的属性“map”

2020-04-22
49

我正在开发一个基于 React 的测验应用程序,我的 map 函数有问题,我使用这个函数为 map 函数级别的问题创建响应按钮。 我收到一条错误消息 “TypeError:无法读取未定义的属性‘map’”

import React, {useState, component} from "react";

const QuestionBox = ({question, options, selected}) => {
  const [answer, setAnswer] = useState(options);
  return (
    <div className="questionBox">
      <p className="question">{question}</p>
      {answer.map((text, index) => (
        <button
          key={index}
          className="answerBtn"
          onClick={() => {
            setAnswer([text]);
            selected(text);
          }}
        >
          {text}
        </button>
      ))}

    </div>
  );
};

export default QuestionBox;
2个回答

当您使用 setAnswer 设置对象时,Answer 也是从选项中设置的。因此,我将 Answer.map 替换为 options.map,并从 setAnswer 中删除数组符号。请尝试此代码。

import React, {useState, component} from "react";

const QuestionBox = ({question, options, selected}) => {
  const [answer, setAnswer] = useState({});
  return (
    <div className="questionBox">
      <p className="question">{question}</p>
      {options.map((text, index) => (
        <button
          key={index}
          className="answerBtn"
          onClick={() => {
            setAnswer(text);
            selected(text);
          }}
        >
          {text}
        </button>
      ))}

    </div>
  );
};

export default QuestionBox;
Khabir
2020-04-22

在挂载时, options 属性未定义,并且您正在用它初始化 answer 。您只需在映射前添加一个检查条件即可:

return (
  <div className="questionBox">
    <p className="question">{question}</p>
    {answer ? answer.map((text, index) => (
    <button
      key={index}
      className="answerBtn"
      onClick={() => {
        setAnswer([text]);
        selected(text);
      }}
    >
      {text}
    </button>
  )) : null}

  </div>
);

或者,如果该属性不存在,则使用默认“options”数组对其进行初始化。

const QuestionBox = ({question, options = ['Default Value'], selected}) => {...

const [answer, setAnswer] = useState(options ? options : ['Default Value']);
bilwit
2020-04-22