ReactJs 无法从 FETCH 获取对象的值
2019-10-17
193
我已经实现了获取并将其设置为对象。但是,当我想获取它的值时。它显示未定义,我对此一无所知。这是代码。
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": "[email protected]",
"title": "How To Make Money",
"slug": "how-to-make-money",
"answer": 0,
"checked": 0,
"status": "",
"waktu": "2019-10-16 04:45:30"
}
]
}
这是错误
TypeError: Cannot read property 'title' of undefined
我非常感谢任何答案。谢谢。
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>
);
cjbt
2019-10-17
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;
Vikas chhabra
2019-10-17
这可能是最初渲染时的问题。 在 api 调用之前可能没有数据。
您需要在使用它之前进行检查
{ object && object.data[0]}
或者您可以在没有数据时显示加载
if (!data) return <span>Loading...</span>
Vinod Sai
2019-10-17