使用 'react-3d-viewer' 在 nextjs 中加载 gltf 文件

loading gltf file in nextjs using 'react-3d-viewer'

我正在尝试使用 npm 'react-3d-viewer' 在 nextjs 中加载 gltf 文件。gltf 文件来自数据库。

   import {GLTFModel,AmbientLight,DirectionLight} from 'react-3d-viewer'
    import React, { Suspense } from "react";
    import getConfig from "next/config";
    import axios from "axios";
    const config = getConfig();
    class ModalDemo extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                apiUrl: config.publicRuntimeConfig.publicRuntimeConfigValue.apiUrl,
                filePath: '',
            };
    
    
        }
     
    
        render() {
    
            return (
                <div className="App">
                    <div>
                        <p>okay</p>
                          <GLTFModel
                    src={this.state.apiUrl + '/api/v1/visitImageRequirementInfo/getImageByImagePathId?imagePath=' + this.state.filePath}>
                    <AmbientLight color={0xffffff}/>
                    <DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/>
                    <DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/>
                </GLTFModel>
                    </div>
    
                </div>
            );
        }
    }

export default ModalDemo;

filePath 属性包含 gltf 的值,其值如下

visitImageDirectory/4f2f0f63-e57b-4eb8-b3d5-c4a2413cd2bd.gltf

它来自数据库的 componetDidMount 函数中的 get 请求。我收到的都是这个错误:

ReferenceError: window is not defined

这是我的 next.config.js 文件,如果它与它有任何关系的话

const withCSS = require('@zeit/next-css');
const withImages = require('next-images');

const withPlugins = require('next-compose-plugins');
module.exports = withPlugins([
    [withCSS, { cssModules: true  }],
    [withImages],
], {
    serverRuntimeConfig: {   serverRuntimeConfigValue: 'test server'  },
    // publicRuntimeConfig: {   publicRuntimeConfigValue: {apiUrl:'http://127.0.0.1:5000'} },
    publicRuntimeConfig: {   publicRuntimeConfigValue: {apiUrl:process.env.apiUrl.trim()} },
    webpack: (config, options) => {   return config;   } ,exportTrailingSlash: true
});

我该如何解决这个问题。或者我可以用来显示 gltf 文件是来自数据库的 nextjs 的任何其他库?

您收到此错误是因为库正在访问服务器上的 window 属性,因为 Next.js 呈现组件服务器端。所以你可以在这里做的最好的事情(如果你不介意这个特定组件的服务器端好处)是使用 动态导入和 ssr: false.

import dynamic from 'next/dynamic';


const AmbientLight = dynamic(() =>
  import('react-3d-viewer').then((mod) => mod.AmbientLight),{ssr: false}
)

const GLTFModel = dynamic(() =>
  import('react-3d-viewer').then((mod) => mod.GLTFModel),{ssr: false}
)

const DirectionLight = dynamic(() =>
  import('react-3d-viewer').then((mod) => mod.DirectionLight),{ssr: false}
)