React JS 服务器端问题 - 找不到窗口 [英] React JS Server side issue - window not found

查看:27
本文介绍了React JS 服务器端问题 - 找不到窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 reactJS 项目中使用 react-rte.我有服务器端渲染,每次我想使用这个包时,我都会得到:

Hi I'm trying to use react-rte in my reactJS project. I have server side rendering and every time I want to use this package I get:

return /msie [6-9]/.test(window.navigator.userAgent.toLowerCase());
                               ^
ReferenceError: window is not defined

我想问题可能出在同构工具上,但我不知道如何将导入包推迟到已经定义窗口的客户端.

I guess the problem might be with isomorphic-tools but I don't know how to defer importing package to the client where window is going to be defined already.

推荐答案

如果您在进行服务器端渲染,那么全局窗口对象很有可能是未定义的,因为只有客户端才能理解.

If you're doing server side rendering, there's a good chance that the global window object is going to be undefined because that is only something the client will understand.

注意:最初,当你启动你的项目时,它会渲染出一个完整的 DOM 字符串(此时它不会知道 window 因为它是服务器端,但随后使用您的窗口对象可用的客户端代码重新渲染!

Note: Initially, when you start up your project its going to render out a complete string of your DOM (at this point it will not know about window because it is server side, but then re-render with the client-side code to which your window object will be available!

在这种情况下,我使用了一种解决方法.这是我的 webpack 插件:

There is a workaround that I am using in this case. This is what I have for my webpack plugin:

new webpack.DefinePlugin({
  'process.env.NODE_ENV': isDevelopment ? '"development"' : '"production"',
  'process.env.BROWSER': JSON.stringify(true),
  __DEV__: isDevelopment
}),

所以我使用 process.env.BROWSER 对我有利,因为它会被定义为 undefined 如果它是服务器端,它会是 true 如果客户端完成渲染.

So I use process.env.BROWSER to my advantage because it will be defined as undefined if it is server side, and it will be true if the client side is done rendering.

因为当服务器端没有窗口对象时一切都停止工作,我们可以添加以下内容:

Since everything just stops working when there isn't a window object on the server side we can add this:

const mySpecialWindowFunction = () => {

  /* START HACK */
  if (!process.env.BROWSER) {
    global.window = {}; // Temporarily define window for server-side
  }
  /* END HACK */

  return /msie [6-9]/.test(window.navigator.userAgent.toLowerCase());
};

这样,您的控制台就不会对您大喊大叫,也不会停止服务器端渲染,您现在可以继续您美好的一天!虽然我不得不承认这有点hacky,但它完成了工作,因为我们想要做的就是让服务器端渲染出初始 DOM 字符串,然后让客户端取结束.

That way, your console won't scream at you and doesn't stop the server side rendering, to which you can now carry on with your glorious day! Although I have to admit that this is a bit Hacky, but it gets the job done because all we want to do is let the server side render out the initial DOM string and then let the client-side take over.

另外注意:不用担心设置window为空对象,客户端渲染完成后会恢复正常.

Also Note: Don't worry about setting window as an empty object, it will be back to normal once the client-side finishes rendering.

这篇关于React JS 服务器端问题 - 找不到窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆