[英]NextJS React Firestore Cannot read properties on first load
I am working on a React NextJS project with Firebase v9 with THREE.JS. I am trying to load the following:我正在使用 Firebase v9 和 THREE.JS 开发 React NextJS 项目。我正在尝试加载以下内容:
const texture = useTexture(floorDoc.url)
The issue I am facing is on the first load.我面临的问题是第一次加载。 I get an error in my console saying, "TypeError: Cannot read properties of undefined (reading 'url')," a common error for an undefined element, even though it is defined in my Firestore DB.我在控制台中收到一条错误消息:“TypeError:无法读取未定义的属性(读取‘url’)”,这是未定义元素的常见错误,即使它已在我的 Firestore 数据库中定义。
If I replace (floorDoc.url) with a general website string then reload and re-add (floorDoc.url) back into my code it reads the correct Firestore document perfectly and works as intended so I am lost as to why it cant fetch on the first request.如果我将 (floorDoc.url) 替换为通用网站字符串,然后重新加载并重新添加 (floorDoc.url) 到我的代码中,它会完美读取正确的 Firestore 文档并按预期工作,所以我不知道为什么它无法获取第一个请求。
Here is my code:这是我的代码:
export default function FloorComponent({ postRef }) {
const floorRef = postRef.collection('assets').doc('floor');
const [floorDoc] = useDocumentData(floorRef);
const [ref] = usePlane(() => ({
rotation: [-Math.PI / 2, 0, 0],
}));
const texture = useTexture(floorDoc.url)
return (
<mesh rotation={[-Math.PI / 2, 0, 0]}>
<planeBufferGeometry attach="geometry" args={[100, 100]} />
<meshBasicMaterial map={texture}
/>
</mesh>
);
}
Have you tried with a conditional return?您是否尝试过有条件退货?
return texture ? (
<mesh rotation={[-Math.PI / 2, 0, 0]}>
<planeBufferGeometry attach="geometry" args={[100, 100]} />
<meshBasicMaterial map={texture}
/>
</mesh>
) : 'Some fallback...'
`
you should do this server side, export following in the page you want this,你应该做这个服务器端,在你想要的页面中导出以下内容,
export async function getServerSideProps() { const floorRef = await postRef.collection('assets').doc('floor') return { props: { floorRef } } }
and you will find floorRef in props of the component你会在组件的道具中找到 floorRef
export default function FloorComponent({ postRef, floorRef }) { const [floorDoc] = useDocumentData(floorRef); const [ref] = usePlane(() => ({ rotation: [-Math.PI / 2, 0, 0], })); const texture = useTexture(floorDoc.url) return ( <mesh rotation={[-Math.PI / 2, 0, 0]}> <planeBufferGeometry attach="geometry" args={[100, 100]} /> <meshBasicMaterial map={texture} /> </mesh> ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.