2

我正在使用 react-apexcharts 库:https ://github.com/apexcharts/react-apexcharts 。

当我导入一个将 lib 导入页面的组件时,当我导航到它时效果很好(客户端路由)。但是当直接使用 URL 访问页面时,出现错误:

Cannot read property 'document' of undefined
TypeError: Cannot read property 'document' of undefined
at Object.<anonymous> (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:433939)
at Object.<anonymous> (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:433950)
at s (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:395)
at Object.<anonymous> (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:169139)
at s (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:395)
at Object.<anonymous> (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:456290)
at s (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:395)
at C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:769
at C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:780
at C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:143
at Object.<anonymous> (C:\Users\a\Desktop\b\b-client\node_modules\apexcharts\dist\apexcharts.min.js:1:263)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)

值得注意的是,我使用的是使用服务器端渲染的 next.js。

该代码与 IMO 无关,我只是从他们的 github 文档中创建了示例组件:

import Chart from 'react-apexcharts'
import React, { Component } from "react";

class ChartExample extends Component {
constructor(props) {
    super(props);

    this.state = {
        options: {
            chart: {
                id: 'apexchart-example'
            },
            xaxis: {
                categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998]
            }
        },
        series: [{
            name: 'series-1',
            data: [30, 40, 45, 50, 49, 60, 70, 91]
        },
        {
            name: 'series-2',
            data: [90, 210, 105, 50, 43, 99, 333, 4]
        }]
    }
}
render() {
    return (
        <Chart options={this.state.options} series={this.state.series} type="bar" width={500} height={320} />
    )
}
}

export default ChartExample;

我定期导入它:

import ChartExample from "../../components/dashboard/ChartExample";

我怎样才能解决这个问题?我认为这是 next.js 的服务器端渲染的问题

4

2 回答 2

8

解决此问题的一种方法是使用 nextjs 的动态导入

import dynamic from 'next/dynamic'
const Chart = dynamic(() => import('react-apexcharts'), {ssr:false})

没有,您的服务器在第一次启动时仍会抱怨文档,但这不会反映在客户端

于 2019-11-16T09:58:45.720 回答
5

图表库在渲染期间需要一个在 SSR 期间不存在的窗口对象。

我建议查看https://github.com/zeit/next.js/#dynamic-import(带有选项{ssr: false})以跳过服务器上的渲染。此外,该库未加载到服务器上,这减少了您的捆绑包大小......

于 2018-12-23T16:47:31.597 回答