Using Lodash with create-react-app results in "Uncaught TypeError: _this.reduce is not a function"

Using Lodash with create-react-app results in "Uncaught TypeError: _this.reduce is not a function"

我是 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 只是将 this 替换为 undefined。在全局范围的函数内部,this 也是 undefined.

在 class 内部 this 指的是 class 的实例,如果您直接在 class 定义的方法内部,或者在构造函数中。

总而言之,长话短说,您需要弄清楚这实际上指的是什么。很可能你只需要将你的数组分配给一个变量并执行:

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();

根据我的经验,阅读起来稍微容易一些。