React/Next.js 似乎不适用于 Apexcharts

React/Next.js doesn't seem to work with Apexcharts

问题

My Next.js/React/Node 当我在任何文件中 import Chart from "react-apexcharts" 时应用程序崩溃。尝试访问该应用会导致以下错误:
Server Error
ReferenceError: window is not defined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
(请参阅调用堆栈下面)。
无论导入的 <Chart/> 是在页面中呈现还是只是未使用,都会发生这种情况。有趣的是,如果我保存文件并启动 Next.js 快速刷新,我的应用程序开始正常工作(有时)。但是,当我刚刚启动应用程序并尝试访问它时,或者当我使用 f5 手动刷新时,会发生上述错误。基本上,它仅在 Next.js 快速刷新后起作用(有时,大概是随机的,它在这种情况下也不起作用,抛出与以前相同的错误)。

环境

Node.js (14.16.0), React (17.0.2), Express (4.17.1), Next.js (10.2.0), react-apexcharts (1.3.9 ), apexcharts (3.26.3), Edge 浏览器, Win10.
Next.js 服务器与 Express 服务器集成在一起。

日志记录

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\georg\Documents\development\web\projects\Angelina-Website\node_modules\apexcharts\dist\apexcharts.common.js:6:345884)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)   
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)        
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)     
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\georg\Documents\development\web\projects\Angelina-Website\node_modules\react-apexcharts\dist\react-apexcharts.min.js:1:722)      
    at Module._compile (internal/modules/cjs/loader.js:1063:30)   
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)        
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)     
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.react-apexcharts (C:\Users\georg\Documents\development\web\projects\Angelina-Website\.next\server\pages\partner\dashboard.js:4973:18)
    at __webpack_require__ (C:\Users\georg\Documents\development\web\projects\Angelina-Website\.next\server\webpack-runtime.js:25:42)

您应该使用此导入它:

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('yourcomponent using react apex-charts'),
  { ssr: false }
)

因为使用了window,它不能在启用 ssr 模式的情况下工作

出现上述问题是因为您创建了启用了 SSR 的 next.js 应用程序

要解决此问题,您需要在禁用 SSR 的情况下动态导入 apex-charts 组件。

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