当 API fetch 返回 HTML 特殊实体(例如 ")时,如何正确显示元素?



我正在从一个trivia api中获取数据,但是我检索的数据的格式不是我可以轻松显示的,我如何获取/存储数据有问题吗?什么是简单的解决方案?

正在获取&存储

React.useEffect(() => {
fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium")
.then(res => res.json())
.then(info => setData(info.results.map(item => {
return { 
type: item.type, 
question: item.question, 
correct_answer: item.correct_answer, 
incorrect_answers: item.incorrect_answers,
id: nanoid() 
}})))
}, [])

当前如何显示原始数据的示例

{
"type": "multiple",
"question": "What is the German word for "spoon"?",
"correct_answer": "Löffel",
"incorrect_answers": [
"Gabel",
"Messer",
"Essstäbchen"
],
"id": "8IfTTvpoQd8DaJ1Hx941a"
},

从上面可以看出,它将数据显示为其原始的特殊实体。

您可以按照命令安装软件包'he'

npm安装

js 中的

import { decode } from 'he';
const json = {
type: 'multiple',
question: 'What is the German word for "spoon"?',
correct_answer: 'Löffel',
incorrect_answers: ['Gabel', 'Messer', 'EssstÄbchen'],
id: '8IfTTvpoQd8DaJ1Hx941a',
};
const jsonString = JSON.stringify(json, null, 4);
const decodedString = decode(jsonString)

在您的HTML 中

<pre>
<code>{decodedString}</code>
</pre>

最新更新