React JSON 未定义
React JSON is undefined
我正在从 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>
行没有显示任何内容。
我不知道为什么会这样,也不知道如何访问我的变量。
谢谢。感谢您的帮助
数据是数组形式还是对象形式?
您将初始状态定义为数组 ad,因此您不能这样做
// you can't do json.email if you expect the response as and array
const [json, setJSON] = useState([]);
改为
const [json, setJSON] = useState({});
如果它是一个对象。然后在模板中做
{json.data && <h1>{json.data.email}</h1>}
<h1>{json.data && json.data.email}</h1>
而不是
<h1>{json.email}</h1>
我正在从 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>
行没有显示任何内容。
我不知道为什么会这样,也不知道如何访问我的变量。
谢谢。感谢您的帮助
数据是数组形式还是对象形式?
您将初始状态定义为数组 ad,因此您不能这样做
// you can't do json.email if you expect the response as and array
const [json, setJSON] = useState([]);
改为
const [json, setJSON] = useState({});
如果它是一个对象。然后在模板中做
{json.data && <h1>{json.data.email}</h1>}
<h1>{json.data && json.data.email}</h1>
而不是
<h1>{json.email}</h1>