Javascript React-尝试在reduce()函数中引用this.props

Javascript React-尝试在reduce()函数中引用this.props,javascript,reactjs,Javascript,Reactjs,我对JS没有什么经验,我正在学习一个关于React的视频课程。大多数事情都有道理,但我在引用范围方面遇到了一些问题 以下是导师写的内容: const orderIds = Object.keys(this.props.order); const total = orderIds.reduce((prevTotal, key) => { const fish = this.props.fishes[key]; const count = this.props.order[key];

我对JS没有什么经验,我正在学习一个关于React的视频课程。大多数事情都有道理,但我在引用范围方面遇到了一些问题

以下是导师写的内容:

const orderIds = Object.keys(this.props.order);

const total = orderIds.reduce((prevTotal, key) => {
  const fish = this.props.fishes[key];
  const count = this.props.order[key];
  const isAvailable = fish && fish.status === 'available';
  if (isAvailable === true) {
    return prevTotal + count * fish.price;
  } else {
    return prevTotal;
  }
}, 0);
他正在使用箭头功能。这当然有效

我想做同样的事情,但是写一个“普通”函数,因为现在我不想做任何快捷方式:

const orderIds = Object.keys(this.props.order);

const total = orderIds.reduce(
  function(prevTotal, key) {

    const fish = this.props.fishes[key];
    const count = this.props.order[key];
    const isAvailable = fish && fish.status === 'available';

    if (isAvailable === true) {

      return prevTotal + (count * fish.price);

    } else {

      return prevTotal;

    }

  }
, 0);
问题是:

TypeError:这是未定义的

所以这里的参考范围有问题。道具

我通过将第二个参数

,本)

从网上搜索有关引用此的信息

这对reduce()函数不起作用。那么,在我的情况下,人们能做些什么呢?同样,我不想使用较短的箭头函数,因为它就像是学习时不想使用的快捷方式。我在网上搜索过这个函数的作用域,也搜索过reduce()函数,但我看到的示例并不完全符合我的要求,或者我根本不知道如何使用他们正在编写的内容


如果您能帮助我,非常感谢,因为/HW

箭头函数有父作用域,所以这表示父作用域的
,但简单函数没有。您可以使用
.bind(this)

const total=orderIds.reduce(
(功能(prevTotal,键){
const fish=this.props.fishes[key];
const count=this.props.order[key];
const isAvailable=fish&&fish.status==“可用”;
如果(isAvailable==真){
返回prevTotal+(计数*鱼价);
}否则{
返回总数;
}
}).绑定(此)

, 0);您可以按如下方式使用绑定或重写代码:

const orderIds = Object.keys(this.props.order);
const { fishes, order } = this.props;

const total = orderIds.reduce(
  function(total, key) {
    const fish = fishes[key];
    const count = order[key];
    const isAvailable = fish && fish.status === 'available';

    if (!isAvailable) return total;

    return total + (count * fish.price);
  }
, 0);

非常感谢你们两位!非常感谢你们两位!