2016-07-31 50 views
2

我需要在自定义反应组件的shouldComponentUpdate函数中使用shallowCompare函数。我得到以下错误:无法导入react-addons-shallow-compare,Typescript

app.js:95084 Uncaught TypeError: Cannot read property 'shallowCompare' of undefined

我已经安装了反应 - 插件 - 浅比较版本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); 

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

Uncaught ReferenceError: __React is not defined

作为提,我正在使用Typescript 1.8.10。

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

Failed to parse SourceMap

我挺憋屈的这一段时间了。一些帮助将不胜感激。

谢谢!

+0

你有没有试过const shallowCompareCompare = require('react-addons-shallow-compare'); ? – QoP

+0

@QoP我得到一个错误,如果我尝试这样做:'错误TS2349:不能调用一个表达式,其类型缺少一个调用签名。'是不是应该有一个'import'的地方? –

+0

是的,你可以使用import - >'import shallowCompare from'react-addons-shallow-compare'' – QoP

回答

0

import * as shallowCompare from "react-addons-shallow-compare";作品!

如果有人想解释为什么并想编辑这个答案,我会很感激。