为什么我收到这个useLayoutEffect警告(不是在测试中)



我有一个新创建的、几乎为空的next/areact/field项目,带有一个fiber Canvas。每次编译时,它都会抛出以下警告。

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.
at Canvas (C:MyLocalFilesStratumreposcfgnext-updatednode_modules@react-threefiberdistreact-three-fiber.cjs.dev.js:155:3)

下面是说明这个问题的最小例子,下面是package.json:

import { Canvas } from '@react-three/fiber'
export default function Home() {
return (
<div>
<Canvas>
</Canvas>
</div>
)
}

软件包.json

{
"name": "cfgnext-updated",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@react-three/drei": "^9.0.1",
"@react-three/fiber": "^8.0.6",
"babel-plugin-styled-components": "^2.0.6",
"next": "12.1.4",
"react": "18.0.0",
"react-dom": "18.0.0",
"styled-components": "^5.3.5"
},
"devDependencies": {
"eslint": "8.12.0",
"eslint-config-next": "12.1.4"
}
}

当我用其他纤维组件填充画布时,一切似乎都很完美。

有人能告诉我吗:

  1. 这实际上是一个合法的警告吗?如果不是
  2. 有办法消除它吗

tia,票据

上面的评论就是答案。非常感谢。我找错地方了。

这是更新后的代码,分为一个页面和一个动态加载的组件(带有一些新内容以便于查看(。

import dynamic from 'next/dynamic'
import styled from "styled-components"
const Scene = dynamic(
() => import('./scene'),
{ ssr: false }
)
export default function App() {
return (
<div>
<ModelDiv>
<Scene/>
</ModelDiv>
</div>
)
}
const ModelDiv = styled.div`
display: block;
background-color: lightblue;
width: 100%;
height: 100vh;
`;

scene.js:中对应的组件

import { Canvas } from '@react-three/fiber'
import { OrbitControls } from '@react-three/drei'
export default function Scene() {
return (
<Canvas>
<ambientLight intensity={1} />
<directionalLight position={[0, 1, 5]} intensity={1} />
<OrbitControls />
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="yellow" />
</mesh>
</Canvas>
)
}

通过在服务器上运行useLayoutEffect,您可能会发送与应用程序首次在客户端上运行时生成的内容不同的html内容,因此会发出警告。解决此问题的一种方法是不在服务器上呈现使用useLayoutEffect的组件。

可以通过检查是否定义了window对象来执行此操作。当它被定义时,这意味着你的代码正在客户端上运行,只有这样你才应该呈现你的canvas组件。

最新更新