我是 React 和 create-react-app
的新手,我正尝试在我的 App.js
文件中使用 Lodash,但我遇到了一个错误。 未捕获类型错误:_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';
在我的 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
,它应该可以工作。
关于javascript - 在 "Uncaught TypeError: _this.reduce is not a function"中使用 Lodash 和 create-react-app 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867031/