2017-08-24 15 views
0

我是React新手,create-react-app,我試圖在我的App.js文件中使用Lodash,我正在運行進入錯誤。 Uncaught TypeError: _this.reduce is not a function。我在我的index.js文件添加使用Lodash與create-react-app結果爲「Uncaught TypeError:_this.reduce不是函數」

import _ from 'lodash'; 
import shuffle from 'lodash/shuffle'; 
import random from 'lodash/random'; 
import find from 'lodash/find'; 

給我App.js

import Lodash from 'lodash'; 

頂部。

爲了測試我使用從MDN,其工作原理是reduce例如:

var total = [0, 1, 2, 3].reduce(function(sum, value) { 
    return sum + value; 
    }, 0); 

但是使用lodash拋出以上錯誤的行:

var books = _.shuffle(this.reduce((p, c, i) => { 
    return p.concat(c.books); 
    }, [])).slice(0, 4); 

在這種情況下this是一個這樣的陣列:

var data = [ 
    { 
    name: 'Mark Twain', 
    imageUrl: 'images/authors/marktwain.jpg', 
    books: ['The Adventures of Huckleberry Finn'] 
    } 
]; 
+1

爲什麼你使用'this'而不是僅僅使用對象指針'data'? – Pytth

+0

你可以試試:'const self = this;'然後在'_.shuffle'中使用'self'而不是'this'。比如:'self.reduce'。 – RaghavGarg

+0

@Pytth因爲它在'data.selectGame =()=> {....}'的函數定義中。所以'this'應該指'數據',對吧? – MarkyDD

回答

2

根據評論部分,您的this參考不指向您所期望的。

更改爲data它應該工作。

+0

爲了擴展這個:使用'data.selectGame = function(){....}'使用'this'有效,同時使用箭頭函數'data.selectGame =()=> {.... ''不。這是因爲箭頭函數_does沒有綁定自己的'this'_([source](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)) – MarkyDD

0

看看你的代碼,其關鍵字this實際上指的是數組。幾乎不可能我會說。你可以寫一本關於this關鍵字在Javascript中的行爲的書。 _this值是一個babel如何處理this的不同行爲。 考慮這個例子:

console.log(this) 

function someFunction(){ 
    console.log(this); 
    const someSubFunction = function() { 
    console.log(this) 
    } 
    someSubFunction(); 

    const someOtherFunction = () => { 
    console.log(this) 
    } 

    someOtherFunction(); 
} 

someFunction(); 

該代碼是由巴別transpiled到:

"use strict"; 

console.log(undefined); 

function someFunction() { 
    var _this = this; 

    console.log(this); 
    var someSubFunction = function someSubFunction() { 
    console.log(this); 
    }; 
    someSubFunction(); 

    var someOtherFunction = function someOtherFunction() { 
    console.log(_this); 
    }; 

    someOtherFunction(); 
} 

someFunction(); 

通知的this值是如何重新分配給一個稱爲_this變量。

在此示例中,所有日誌語句均打印出undefined。如果您在根範圍使用關鍵字this,則它(幾乎)肯定會是undefined。事實上,如果您查看傳輸示例的第3行,babel就會用undefined代替this。在全球範圍內的函數中,this也是undefined

類內this指的是類的實例,如果您直接在由類定義的方法內或在構造函數中。

無論如何長話短說,你需要弄清楚這實際上是指什麼。最有可能你只需要你的數組賦值給一個變量,並做到:

var books = _.shuffle(data.reduce((p, c, i) => { 
    return p.concat(c.books); 
}, [])).slice(0, 4); 

如果你打算做lodash不過,你也可以是一致的,只是使用lodash這樣的:

var books = _.chain(data) 
    .reduce((p,c,i) => _.concat(c.books), []) 
    .shuffle() 
    .slice(0,4) 
    .value(); 

稍微容易閱讀我的經驗。

相關問題