我是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']
}
];
爲什麼你使用'this'而不是僅僅使用對象指針'data'? – Pytth
你可以試試:'const self = this;'然後在'_.shuffle'中使用'self'而不是'this'。比如:'self.reduce'。 – RaghavGarg
@Pytth因爲它在'data.selectGame =()=> {....}'的函數定義中。所以'this'應該指'數據',對吧? – MarkyDD