【问题标题】:Using Lodash with create-react-app results in "Uncaught TypeError: _this.reduce is not a function"将 Lodash 与 create-react-app 一起使用会导致“未捕获的类型错误:_this.reduce 不是函数”
【发布时间】: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


【解决方案1】:

根据 cmets 部分,您的 this 参考并未指向您所期望的。

将其更改为data,它应该可以工作。

【讨论】:

  • 对此进行扩展:使用data.selectGame = function() {....} 使this 的使用有效,而使用箭头函数data.selectGame = () => {....} 则无效。这是因为箭头函数不绑定自己的this (source)
【解决方案2】:

查看您的代码,关键字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

类内部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();

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

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 2015-07-20
    • 2022-11-23
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多