【问题标题】:In what way does a React / Redux reducer "reduce" things? [duplicate]React / Redux reducer 以什么方式“减少”事物? [复制]
【发布时间】:2021-08-04 08:04:52
【问题描述】:

official Redux docs 中,它说:

“Reducer”函数之所以得名,是因为它们类似于您传递给Array.reduce() 方法的回调函数。

虽然 Array.reduce 可以将 3 或 1000 个数字减少为 1,因此将其“减少”为一个简单的数字:

// reducing it to a single sum:
console.log([1, 3, 5, 7, 9].reduce((a, b) => a + b));

Redux reducer 如何真正“减少”事物?

【问题讨论】:

  • 我猜(a, b) => a + b) 是一个“reducer”,没关系......所以 Redux 看到用户点击订购 2 个汉堡包,1 个软饮料,然后结帐,所有这些操作集中在一起“达到最终状态”是通过减少和减少来完成的吗?好像有点傻……就像我们下棋,或者上学,洗澡,睡觉,还减?这只是一系列的行动,但我没有看到任何减少。或许,如果我们说我们的生命减少到死亡,那么我们可以称之为减少

标签: redux react-redux


【解决方案1】:

Redux reducer 将所有操作的数组归约为一个状态。

const finalState = [
    { type: 'INIT'}, 
    { type: 'SOME_ACTION' }, 
    { type: 'SOME_OTHER_ACTION'} 
  ].reduce(reducer, undefined)

const nextState = [
    { type: 'SOME_ACTION' }, 
    { type: 'SOME_OTHER_ACTION'} 
  ].reduce(reducer, lastState)

【讨论】:

  • 如果我看到购物车包含一个汉堡包,然后是 2 个汉堡包,然后再加上一杯软饮料,我会看到一个“复杂器”。我没有看到“减速器”
  • 这是对Array.prototype.reduce() 的“reducer”参数的一种发挥。
  • 它可以被称为 stateConverter 或 stateMorpher 但我不知道为什么它被称为 reducer,因为它不会减少状态
猜你喜欢
  • 2019-07-23
  • 1970-01-01
  • 2022-01-03
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多