如何防止加载多个 React 副本? [英] How Prevent Multiple Copies Of React from Loading?

查看:20
本文介绍了如何防止加载多个 React 副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的 Meteor 应用程序中,使用 browserify 和 React,一切正常,直到我切换到 meteor网络包.

我在我的 Meteor 应用程序中使用 react-select 并且效果很好,但使用 browserify 我可以防止加载多个 react 副本,从而防止我现在遇到的这个错误:

<前>错误:不变违规:addComponentAsRefTo(...):只有 ReactOwner 可以有 refs.您可能正在向未在组件的 `render` 方法中创建的组件添加 ref,或者您加载了多个 React 副本(详细信息:https://fb.me/react-refs-must-have-owner).

我的 package.json 看起来是这样的:

<代码>...依赖关系":{"classnames": "^2.1.3","lodash": "^3.10.0",反应":^0.14.6","react-dom": "^0.14.6",反应混合":^ 2.0.1",反应选择":^1.0.0-beta8"},...

webpack 中是否有配置我可以使用一些称为 externals 的东西?不完全确定这意味着什么,但评论说使用:

外部:{'反应':'反应','反应-DOM':'反应DOM'}

解决方案

既然你用的是 webpack,你可以添加一个别名来加载 react,像这样:

//在 webpack.config.js 中解决: {别名:{反应:path.resolve('node_modules/react'),},},

这避免了 addComponentAsRefTo(...) 错误并使我们的构建再次成功.但是,由于某种原因,测试构建仅在我们的 CI 环境中失败,因为它无法解析 node_modules/react 路径.不过,我认为您不太可能遇到这个特殊问题.

In my previous Meteor app, using browserify, and React, all was working until I switched to meteor webpack.

I use react-select in my Meteor apps and it worked great but with browserify I could prevent multiple copies of react from loading which prevents this error I'm now having:

Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).

My package.json look this:

...

"dependencies": {
    "classnames": "^2.1.3",
    "lodash": "^3.10.0",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-mixin": "^2.0.1",
    "react-select": "^1.0.0-beta8"
  },

...

Is there a configuration in webpack I could use something call externals? Not fully sure what that means but a comment said to use:

externals: {
  'react': 'React',
  'react-dom': 'ReactDOM'
}

解决方案

Since you use webpack, you can add an alias for loading react, like this:

// In webpack.config.js

  resolve: {
    alias: {
      react: path.resolve('node_modules/react'),
    },
  },

This prevented the addComponentAsRefTo(...) error and made our build succeed again. However, for some reason, the testing build failed only on our CI environment as it could not resolve the node_modules/react path. I think it's unlikely that you will encounter this particular problem, though.

这篇关于如何防止加载多个 React 副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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