【问题标题】:Next.js: window is not definedNext.js:未定义窗口
【发布时间】:2021-10-06 08:12:56
【问题描述】:

我正在尝试将 apexcharts 用于 next.js 应用程序,但它返回给我的窗口未定义。

我很乐意为此提供任何帮助。

有人知道发生了什么以及为什么吗?

import React from 'react';
import Chart from 'react-apexcharts';

export default class Graficos extends React.Component <{}, { options: any, series: any }> {
    constructor(props:any) {
        super(props);

        this.state = {
            options: {
            chart: {
                id: "basic-bar"
            },
            xaxis: {
                categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
            }
            },
            series: [
            {
                name: "series-1",
                data: [30, 40, 45, 50, 49, 60, 70, 91]
            }
            ]
        };
    }
  
    render() {
        return (
            <div className="row">
                <h1>Gráfico Básico</h1>
                <div className="mixed-chart">
                    <Chart
                        options={this.state.options}
                        series={this.state.series}
                        type="bar"
                        width={500}
                    />
                </div>
            </div>
        );
    }
  }

【问题讨论】:

标签: javascript reactjs typescript next.js apexcharts


【解决方案1】:

Next.js 的一个关键特性是它可以在服务器上甚至在构建时渲染您的 React 应用程序的一部分。虽然这有助于提高页面的性能,但缺点是服务器不提供应用程序可以在浏览器中访问的所有相同 API。在这种情况下,没有定义全局 window 对象。

不幸的是,搜索 apexcharts.js 的源代码会发现许多对 window 的引用:https://github.com/apexcharts/apexcharts.js/search?q=window。这也发生在他们的 React 包装器中:https://github.com/apexcharts/react-apexcharts/blob/ecf67949df058e15db2bf244e8aa30d78fc8ee47/src/react-apexcharts.jsx#L5。虽然似乎没有办法让顶点图表避免引用window,但您可以阻止 Next.js 在服务器上使用图表。最简单的方法是包装对代码的任何引用,并检查是否定义了window,例如

<div className="mixed-chart">
  {(typeof window !== 'undefined') &&
  <Chart
    options={this.state.options}
    series={this.state.series}
    type="bar"
    width={500}
  />
  }
</div>  

使用 apexcharts,您还需要为组件导入执行此操作,因为单独的导入将触发对 window 的引用,如第二个链接所示。为了解决这个问题,您需要使用动态导入,而不是您目前拥有的正常导入:https://nextjs.org/docs/advanced-features/dynamic-import

import dynamic from 'next/dynamic'

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

【讨论】:

    【解决方案2】:
    if (typeof window !== "undefined") {
        host = window.location.host;
        console.log("host--------------", host);
      }
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2021-10-26
      • 2022-01-21
      • 2021-12-04
      相关资源
      最近更新 更多