@react-three/react-three-fiber: useLoader() 在 props 更改时加载新文件 [英] @react-three / react-three-fiber: useLoader() to load new file on props change
问题描述
我有一个功能性反应组件并初始加载 gltf 模型 - 路径通过道具 - 这工作正常.
I have a functional react component and initial load a gltf model - the path gets passed through the props - this works fine.
但是如果道具改变组件重新渲染 - 我检查过 - 路径被改变并且应该加载一个新模型 - 但我没有.
But if the props change the component rerenders - I checked that - the path is changed and a new Model should be loaded - but I does not.
如何实现这一目标?如果状态更新,我想交换/替换正在呈现的对象.
我尝试了不同的加载器,将 gltf 自身设置为一个状态,但这些都没有.我想我错过了一个潜在的概念.请帮忙
I tried different loaders, set the gltf it self as a state but none of this wokred. I think I miss an underlying concept. Pls Help
function Character(props) {
const spinner = useRef();
console.log(props.model, "from modelpreviewer");
const gltf = useLoader(GLTFLoader, props.model);
return gltf ? (
<primitive
ref={spinner}
object={gltf.scene}
/>
) : null;
}
字符组件呈现如下:
<Canvas
camera={{ position: [0, 0, 10] }}>
<ambientLight intensity={0.8} />
<spotLight intensity={0.7} position={[300, 300, 400]} />
<Suspense fallback={null}>
<Character model={props.model} />
</Suspense>
</Canvas>
推荐答案
我在渲染纹理时测试了 useLoader
的问题,它对我来说很好.这是一个简单的示例显示只要 props
改变,纹理就会改变.
I test the problem of useLoader
when render the texture and it works fine to me.
This a simple example which shows the texture will change whenever the props
changed.
我猜你错过了 props.model
的正确路径点.也许你可以硬编码一个 props.model
的值来确保文件路径正确与否.
I guess you're miss the correct path point to props.model
. Maybe you can hard code a value of props.model
to make sure the file path is correct or not.
我找到了 gltf 只渲染一次的原因.答案是这里.
I find the reason why gltf just render once. The answer is here.
您不能在 webgl/threejs 中重复使用网格或将同一个对象两次放入场景中,它只会卸载并重新安装.
You can't reuse meshes or put the same object into the scene twice in webgl/threejs, it will just unmount and remount.
另一种解决方案是克隆场景.
const { scene } = useLoader(GLTFLoader, url)
const copiedScene = useMemo(() => scene.clone(), [scene])
我还提供了一个关于 代码沙盒.
I also provide a fixed example on codesandbox.
这篇关于@react-three/react-three-fiber: useLoader() 在 props 更改时加载新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!