我是 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
,它应该可以工作。
查看您的代码,关键字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();
这段代码由 babel 转译为:
"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();
根据我的经验,稍微容易阅读。