我已经实现了访存并将其设置为对象。但是,当我想获得其价值时。它显示未定义,对此我一无所知。这是代码。
import {useEffect,useState} from 'react';
import { useRouter, Router } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';
const Post = (props) => {
const [object, setObject] = useState({});
const router = useRouter();
useEffect(
() => {
const data = router.query;
const FormData = new URLSearchParams();
FormData.append('slug',data.id);
fetch(Settings.api+'viewPost',{
method: 'POST',
body: FormData
})
.then(res=>res.json())
.catch(function(e){
console.log(e)}
)
.then(obj=>{
setObject(obj.data[0])
})
}
, [router.query]
)
return (
<Layout>
<h1>{object.title}</h1> --> I would like to display here
</Layout>
);
}
export default Post;
无论如何,这是我要实现的json
{
"page": 1,
"total": 0,
"data": [
{
"postId": 4,
"boardId": "",
"username": "test@email.com",
"title": "How To Make Money",
"slug": "how-to-make-money",
"answer": 0,
"checked": 0,
"status": "",
"waktu": "2019-10-16 04:45:30"
}
]
}
这是错误
TypeError:无法读取未定义的属性“ title”
我真的很感谢任何回答。谢谢。
答案 0 :(得分:3)
尝试仅记录console.log(object)
,就已经将object
状态的值设置为obj.data[0]
了。
编辑:您可能可以在useEffect触发之前进行检查:
if (!object) {
return <h1>Loading...</h1>
}
console.log(object.data[0])
return (
<Layout>
<h1>{router.query.id}</h1>
</Layout>
);
答案 1 :(得分:1)
这可能是最初渲染时出现的问题。 在api调用之前,它可能没有数据。
您需要先检查它
{ object && object.data[0]}
或者您可以在没有数据时显示加载情况
if (!data) return <span>Loading...</span>
答案 2 :(得分:1)
import {useEffect,useState} from 'react';
import { useRouter, Router } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';
const Post = (props) => {
const [object, setObject] = useState({});
const router = useRouter();
useEffect(
() => {
const data = router.query;
const FormData = new URLSearchParams();
FormData.append('slug',data.id);
fetch(Settings.api+'viewPost',{
method: 'POST',
body: FormData
})
.then(res=>res.json())
.catch(function(e){
console.log(e)}
)
.then(obj=>{
setObject(obj.data[0])
})
}
, [router.query]
)
//console.log(object.data[0]); --> does not work here
return (
<Layout>
<h1>{router.query.id}</h1>
</Layout>
);
}
export default Post;