2016-07-31 78 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";作品!

如果有人想解釋爲什麼並想編輯這個答案,我會很感激。