当我刷新页面时,我无法读取未定义的属性,但只有当我刷新页面时。我只是在想我需要做些什么来解决这个问题?
import Header from "../components/Header.js";
import Footer from "../components/Footer.js";
import { useRouter } from "next/dist/client/router";
import { format } from "date-fns";
import Image from "next/image";
import { db } from "../firebase.js";
import firebase from 'firebase';
import React, { useHook, useEffect, useState } from 'react';
function View() {
const router = useRouter();
const { id } = router.query;
const[result, setResults] = useState('');
useEffect(() => {
db.collection('results').doc(id).get()
.then(snapshot => setResults(snapshot.data()))
}, []);
return (
<div>
<Header />
<main className="pb-14">
<div className="flex">
<section className="flex-grow pt-10 pb-7 px-6">
<h1 className="text-3xl font-semibold mt-2 mb-6">
{ result.title }
</h1>
</section>
</div>>
</main>
<Footer />
</div>
)
}
export default View
事实上,您的问题与useEffect
无关。你只需要检查一下装货台上的result
。
你试图访问result.title
,但结果值是undefined
,所以它变成了undefined.title
,这是不正确的。
试试这个:
import Header from "../components/Header.js";
import Footer from "../components/Footer.js";
import Loading from "../components/Loading.js";
import { useRouter } from "next/dist/client/router";
import { format } from "date-fns";
import Image from "next/image";
import { db } from "../firebase.js";
import firebase from 'firebase';
import React, { useHook, useEffect, useState } from 'react';
function View() {
const router = useRouter();
const { id } = router.query;
const[result, setResults] = useState(undefined);
useEffect(() => {
db.collection('results').doc(id).get()
.then(snapshot => setResults(snapshot.data()))
}, []);
if (typeof result === 'undefined'){
return <Loading />
}
return (
<div>
<Header />
<main className="pb-14">
<div className="flex">
<section className="flex-grow pt-10 pb-7 px-6">
<h1 className="text-3xl font-semibold mt-2 mb-6">
{ result.title }
</h1>
</section>
</div>>
</main>
<Footer />
</div>
)
}
export default View
PS:另外,你可以为加载阶段设置一个布尔状态