【发布时间】:2021-06-26 21:57:31
【问题描述】:
我正在从 API 获取这个 JSON:
{
"data": {
"email": "test@tre.com",
"inserted_at": "2021-03-30T15:37:06",
"links": [
{
"id": 1,
"title": "My link title",
"url": "http://google.com"
},
{
"id": 2,
"title": "My Youube title",
"url": "http://youtube.com"
}
]
}
}
我正在使用 Hooks 以这种方式获取它:
export default function Notes() {
const [json, setJSON] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/api/users/1", {
method: "GET"
})
.then((response) => response.json())
.then((json) => {
// console.log(data);
setJSON(json);
})
.catch((err) => {
console.error(err);
});
}, [setJSON]);
然后我尝试像这样展示它:
return (
<>
<div className="content">
{JSON.stringify(json)}
<h1>{json.email}</h1>
</div>
</>
);
{JSON.stringify(json)} 行显示 JSON。
但是<h1>{json.email}</h1> 行没有显示任何内容。
我不知道为什么会发生这种情况以及如何访问我的变量。
谢谢。感谢您的帮助
【问题讨论】:
-
错字:你忘记了结构的
data.部分。 -
是的,但是它说 json.data 未定义。我不知道为什么。我输入了 json.data.email
-
这能回答你的问题吗? Reactjs async rendering of components 虽然它使用类组件,但问题/解决方案是相同的。获取是异步的,因此
data在可用之前是未定义的,因此您必须在使用数据之前处理该状态(加载)。 -
试试 {json &&
{json.email}
} -
不是真的(:我没有使用 Ajax
标签: json reactjs react-hooks undefined