如何解决@react-three/drei 的东西不适用于 next.js
我不能使用 drei 材料和其他东西,例如 MeshWobbleMaterial 或 MeshDistortMaterial 甚至 ContactShadows,我总是得到一个错误,例如:
react-three-fiber.esm.js:1383 Uncaught TypeError: 无法读取 null 的属性“getState” 在 useFrame (react-three-fiber.esm.js:1383) 在 MeshDistortMaterial.js:72 (在 MeshDistortMaterial 的情况下)
它所指的这个 null 是 react-three-fiber 上 useFrame 模块内的一个“useContext(context)”。 我认为这与我也在使用下一个版本 10.1.3 的事实有关。
完整代码如下:
import { useRef,useState,useMemo } from 'react'
import { Canvas } from 'react-three-fiber'
import { Box,MeshDistortMaterial } from '@react-three/drei'
import * as THREE from 'three'
import MyCamera from '../three/MyCamera'
//HERES WHERE THE MATERIAL IS USED
const MyBox = function (props) {
const mesh = useRef()
const [hovered,setHover] = useState(false)
const [active,setActive] = useState(false)
return (
<Box
args={[1,1,1]}
{...props}
ref={mesh}
scale={active ? [6,6,6] : [5,5,5]}
onClick={() => setActive(!active)}
onPointerOver={() => setHover(true)}
onPointerOut={() => setHover(false)}
castShadow
>
<MeshDistortMaterial
attach="material"
distort={1} // Strength,0 disables the effect (default=1)
speed={10} // Speed (default=1)
/>
</Box>
)
}
//HERES JUST THE CANVAS STUFF
export default function Main() {
const dirLight = useMemo(()=>{
const light = new THREE.DirectionalLight('white');
light.castShadow=true;
//Set up shadow properties for the light
light.shadow.mapSize.width = 10240 // default
light.shadow.mapSize.height = 10240 // default
light.shadow.camera.near = 0.1 // default
light.shadow.camera.far = 5000 // default
light.shadow.camera.top = -100 // default
light.shadow.camera.right = 100 // default
light.shadow.camera.left = -100 // default
light.shadow.camera.bottom = 100 // default
return light
},[])
return (
<div className="canvasContainer">
<Canvas
linear = "true"
frameloop="demand"
shadows = "true"
shadowMap
>
<MyCamera position={[0,30]} infLimit={-1000} supLimit ={0} />
<ambientLight intensity={0.2}/>
<primitive object={dirLight} position={[30,30]} />
<primitive object={dirLight.target} position={[0,0]} />
<mesh receiveShadow position={[0,-2]}>
<planeBufferGeometry attach="geometry" args={[1000,1000]} />
<meshStandardMaterial attach="material" color="gray" />
</mesh>
<MyBox position={[8,0]}/>
</Canvas>
</div>
)
}
有办法解决吗?
我知道使用 next 您需要安装 next-transpile-modules 并创建下一个配置文件。我这样做了,这是我的 next.config.js
const withTM = require('next-transpile-modules')(['three','@react-three/drei'])
module.exports = withTM()
非常感谢您的帮助,使用 next.js 很难解决这个问题。
解决方法
您是否尝试在 Canvas 的子项中设置 useMemo?
我的猜测是您从场景上下文中实例化了一个 DirectionalLight。 这可能会导致此错误。
,澄清一下,我是在正确的道路上,但有些软件包使这个错误发生,一段时间后无法解决这个问题,我卸载并安装了所有依赖项,并且其中很多都在此期间更新这次,它正常工作了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。