无法导入react-addons-shallow-compare,Typescript

时间:2016-07-31 20:08:25

标签: reactjs typescript import webpack source-maps

我需要在自定义反应组件的shouldComponentUpdate函数中使用shallowCompare函数。我收到以下错误:

  

app.js:95084 Uncaught TypeError:无法读取未定义的属性“shallowCompare”

我已经安装了react-addons-shallow-compare版本15.3.0,我在node_modules中找到了它。它看起来像这样:

module.exports = require('react/lib/shallowCompare');

这是引用的shallowCompare.js。

/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
* @providesModule shallowCompare
*/

'use strict';

var shallowEqual = require('fbjs/lib/shallowEqual');

/**
 * Does a shallow comparison for props and state.
 * See ReactComponentWithPureRenderMixin
 * See also https://facebook.github.io/react/docs/shallow-compare.html
 */
function shallowCompare(instance, nextProps, nextState) {
  return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
}

module.exports = shallowCompare;

我还安装了打字机。我有这个版本:

// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6a36f6d5b61602b6c4ad932599097135e80abaf4/react/react-addons-shallow-compare.d.ts
declare namespace __React {
    namespace __Addons {
        export function shallowCompare<P, S>(
            component: __React.Component<P, S>,
            nextProps: P,
            nextState: S): boolean;
    }
}

declare module "react-addons-shallow-compare" {
    var shallowCompare: typeof __React.__Addons.shallowCompare;
    export = shallowCompare;
}

现在我正在尝试导入它并在我的一个文件中使用它。我已尝试过每种导入它的策略。

import { __Addons as ReactAddons } from "react";

/* ... other stuff ... */

ReactAddons.shallowCompare(this, nextProps, nextState);

或者

import shallowCompare = require("react-addons-shallow-compare");

/* ... other stuff ... */

shallowCompare(this, nextProps, nextState);

或者

import shallowCompare = __React.__Addons.shallowCompare;

/* ... other stuff ... */

shallowCompare(this, nextProps, nextState);

在最后一种情况下,我得到的错误不是上面提到的错误,而是

  

未捕获的ReferenceError:未定义__React

提及,我使用的是Typescript 1.8.10。

对于它的价值,我也收到以下错误:

  

无法解析SourceMap

我现在已经坚持了一段时间。一些帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

import * as shallowCompare from "react-addons-shallow-compare";有效!

如果有人想解释原因并希望编辑这个答案,我将非常感激。