umi-plugin-keep-alive icon indicating copy to clipboard operation
umi-plugin-keep-alive copied to clipboard

umi 服务端渲染下报window is not defined 错误

Open supwjm opened this issue 4 years ago • 9 comments

umi 服务端渲染下报window is not defined 错误

C8962E9D-21C5-49FA-9E3F-BB5BF26F08CE

supwjm avatar Oct 23 '20 09:10 supwjm

+1

h5m1007 avatar Oct 28 '20 10:10 h5m1007

试试 v0.0.1-beta.17

CJY0208 avatar Oct 29 '20 03:10 CJY0208

找到报错的地方在 umi packages/renderer-react/src/renderRoutes/renderRoutes.tsx 下const defaultPageInitialProps = opts.isServer ? {} : (window as any).g_initialProps; 在服务端渲染的时候opts.isServer为undefined,导致了调window报错。发现安装 umi-plugin-keep-alive 之后访问任何一个页面都会报错,估计插件某个地方使opts.isServer获取错误导致。

supwjm avatar Oct 29 '20 06:10 supwjm

能否提供可复现 demo 项目?我这边的用例没有复现这个问题,SSR 功能和 KeepAlive 可以同时用的

CJY0208 avatar Nov 03 '20 02:11 CJY0208

可以试着从这个线上 demo 中 fork

https://codesandbox.io/s/umi-keep-alive-tabs-demo-forked-7c1nz

CJY0208 avatar Nov 03 '20 02:11 CJY0208

请问解决方案是什么 我也遇到了这个问题

tanwei0425 avatar Nov 06 '20 02:11 tanwei0425

我试了一下,确实会有这个报错,不过我尝试了一下直接使用react-activation,目前来看也没问题的,以下是我的使用方式:

src/app.tsx中新增如下代码:

import React from "react";
import { AliveScope } from 'react-activation';

export function rootContainer(container: React.ReactNode) {
  return (
    <AliveScope>
      {container}
    </AliveScope>
  );
}

页面上导出时使用KeepAlive包裹

import styles from './index.less';
import { Button } from 'antd';
import { Helmet, history } from 'umi';
import { useCounter } from 'ahooks';
import { KeepAlive } from 'react-activation';

export function IndexPage() {
  const [counter, { inc }] = useCounter(30);

  return (
    <>
      <Helmet>
        <title>首页</title>
      </Helmet>
      <div>
        <Button onClick={() => { inc() }}>Hello {counter}</Button>
        <h1 className={styles.title}>Page index</h1>
        {
          [...Array(counter)].map((_, index) => (<div onClick={() => history.push('/u/h')} key={index}>hello {index}</div>))
        }
      </div>
    </>
  );
}

export default () => (
  <KeepAlive name='/startpage'>
    <IndexPage />
  </KeepAlive>
)

最后将作者的babel插件启用,在.umirc.ts中增加如下代码

import { defineConfig } from 'umi';

export default defineConfig({
  extraBabelPlugins: [
    'react-activation/babel',
  ],
});

smilecc avatar Feb 03 '21 16:02 smilecc

过往 react-activation 由于未能主动修复上下文断层问题,所以 umi 插件形态的实现也颇为麻烦

0.8.0 以后 activation 增加了自动修复上下文断层功能,umi 插件形态可以简化为楼上的样子,可以解决许多问题

后续尝试把简化形态应用于本仓库中

CJY0208 avatar Feb 04 '21 01:02 CJY0208

+1

ibandeng avatar Mar 16 '21 08:03 ibandeng