Reaction-以列表形式显示答案

iqxoj9l9  于 2022-10-15  发布在  React
关注(0)|答案(4)|浏览(181)

我正在创建一个Reaction测验应用程序,但我正在试图弄清楚如何将我的答案数组显示为列表。到目前为止,这是我的代码
Load Data成功地从API加载数据,当我在Answers变量上执行控制台日志时,我可以看到每个问题都有一个数组,其中有四个答案,这是正确的。

const loadData = async () => {
  let response = await fetch(
    "https://opentdb.com/api.php?amount=10&category=22&difficulty=medium&type=multiple"
  );
  const data = await response?.json();
  console.log(data);

  const getQuestions = data.results.map((item) => {
    const question = item.question;

     const answers = [...item.incorrect_answers, item.correct_answer];

//console.log(answers) shows this as an example 
 ["Quebec", "Ontario", "Nova Scotia", "Alberta"]

    return {
      question: question,
      answers: answers,
    };
  });
  return getQuestions;
};

function App() {
//create useState hook to pass data into
const [showData, setData] = useState([]);

//pass the data into a useeffect hook and setData to the loadData method from above
useEffect(() => {
    (async () => {
      const getData = await loadData();
      setData(getData);

    })();
  }, []);

  return (
    <React.Fragment>
      {showData.map((data) => (
        <>
          <div>
            <h1>{data.question}</h1>

          <ul>{data.answers}</ul>
         </div>
        </>
      ))}

    </React.Fragment>
  );
}

Return函数输出问题,但如果我尝试将答案显示为列表,以便可以分别获得每个答案,它只会将它们放在同一行上。
瑞士的首都是哪个城市?苏黎世,法兰克福,维也纳,伯尔尼
如有任何帮助,我们将不胜感激:)

5lhxktic

5lhxktic1#

您应该迭代答案数组,而不是直接呈现它们。另外,ul是无序列表的父标签,您应该使用li来列出子列表。

import { useEffect, useState } from "react";

export default function App() {
  const [showData, setData] = useState([]);
  const loadData = async () => {
    let response = await fetch(
      "https://opentdb.com/api.php?amount=10&category=22&difficulty=medium&type=multiple"
    );
    const data = await response?.json();
    console.log(data);

    const getQuestions = data.results.map((item) => {
      const question = item.question;
      const answers = [...item.incorrect_answers, item.correct_answer];
      return {
        question: question,
        answers: answers
      };
    });
    return getQuestions;
  };

  useEffect(() => {
    (async () => {
      const getData = await loadData();
      setData(getData);
    })();
  }, []);

  return (
    <>
      {showData.map((data,i) => (
        <>
          <div key={i}>
            <h4>{data.question}</h4>
            // map the answers separately
            {data.answers.map((item,j)=><li key={j}>{item}</li>)}
          </div>
        </>
      ))}
    </>
  );
}

这里的校验码:https://codesandbox.io/s/floral-leftpad-zcwew?file=/src/App.js:0-1063

jtoj6r0c

jtoj6r0c2#

您可以使用另一个map迭代您的answers数组:

<ul>
  {
    data.answers.map((answer) =>
       // It's a good practice to apply a unique identifier as key to your list
       // Not the index, however, as it may change 
       <li key={someValue}>answer</li> 
    ) 
  }
</ul>
mkshixfv

mkshixfv3#

体验🙋🏻‍♂️

function App() {
  //create useState hook to pass data into
  const [showData, setData] = useState([]);

  //pass the data into a useeffect hook and setData to the loadData method from above
  useEffect(() => {
    (async () => {
      const getData = await loadData();
      setData(getData);
    })();
  }, []);

  return (
    <React.Fragment>
      {showData.map((data, index) => {
        return (
          <div key={index}>
            <div>
              <h1>{data.question}</h1>
              <ul>
              {data.answers.map((answer, index) => {
                return (
                  <li key={index}>{answer}</li>
                )
              })}
              </ul>
            </div>
          </div>
        );
      })}
    </React.Fragment>
  );
}

export default App;
px9o7tmv

px9o7tmv4#

这里有多个问题:
1.<ul>{data.answers}</ul>不起作用,因为data.answers是数组。您需要将此数组的元素Map到<li>元素,就像在父数组中所做的那样。
1.每当使用map创建列表时,必须在每个元素上添加唯一的键,通常是一个id。我假设问题和答案是唯一的,所以您可以使用数据本身作为关键。
1.您的代码在访问response.json()之前不检查response.ok。是的,您在这里确实使用了问号操作符,以便特定操作是安全的,但随后下一行上的undefined.results崩溃,因此它只会推低错误并进一步混淆fetch错误。
1.去掉多余的片段<>
1.在ES6中,{questions: questions}只能是{questions}
1.当你继续使用这款应用时,不要忘记打乱你的答案。

<script type="text/babel" defer>
const {Fragment, useEffect, useState} = React;

const loadData = async (
  url="https://opentdb.com/api.php?amount=10&category=22&difficulty=medium&type=multiple"
) => {
  const response = await fetch(url);

  if (!response.ok) {
    throw Error(response.status);
  }

  return (await response.json()).results.map(
    ({question, incorrect_answers, correct_answer}) => ({
      question,
      answers: [...incorrect_answers, correct_answer]
    })
  );
};

const App = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    loadData()
      .then(setData)
      .catch(err => console.error(err))
    ;
  }, []);

  return (
    <Fragment>
      {data.map(({question, answers}) => (
        <div key={question}>
          <h3>{question}</h3>
          <ul>
            {answers.map(a => <li key={a}>{a}</li>)}
          </ul>
        </div>
      ))}
    </Fragment>
  );
}

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<App />);

</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

相关问题