【发布时间】:2018-02-02 15:44:26
【问题描述】:
我是 React 和 create-react-app 的新手,我正在尝试在我的 App.js 文件中使用 Lodash,但遇到了错误。 Uncaught TypeError: _this.reduce is not a function。我添加了
import _ from 'lodash';
import shuffle from 'lodash/shuffle';
import random from 'lodash/random';
import find from 'lodash/find';
到我的App.js 的顶部和
import Lodash from 'lodash';
在我的index.js 文件中。
为了测试,我使用了来自 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? -
你能不能试试:
const self = this;然后在_.shuffle中使用self而不是this。喜欢:self.reduce. -
@Pytth 因为它在
data.selectGame = () => {....}的函数定义中。所以this应该是指data吧? -
@MarkyDD:不;
() =>为您提供this其定义。 -
我不知道@SLaks。我将
this的所有引用更改为data,它现在可以工作了。 @Pytth 或@SLaks,您应该为此创建一个答案,我会接受它。感谢您的帮助!
标签: javascript reactjs lodash create-react-app