【问题标题】:Why do we use () => [] instead of []?为什么我们使用 () => [] 而不是 []?
【发布时间】:2018-09-11 08:43:35
【问题描述】:

我有一个关于 React Native 中的 reducer 的简短问题

为什么一定要这样写代码:

import { combineReducers } from 'redux';

export default combineReducers({
    reducerKey : () => []
});

而不是这个:

import { combineReducers } from 'redux';

export default combineReducers({
    reducerKey : []
});

基本上:为什么它必须是一个函数? 谢谢!

【问题讨论】:

  • 没有必要。您可以使用第二个版本,大多数人更喜欢这个
  • reducer 是一个返回值的函数。如果您不想要函数,只需输入您想要的值即可。
  • 实际上我尝试了第二个,但是没有用(react-native)

标签: javascript reactjs react-native redux


【解决方案1】:

reducer 的工作是应用一些输入来更新状态。执行操作后,reducer 返回新状态。它适用于输入,并且可能在不同的输入上返回不同的状态,因此它是一个函数。

如果您使用第二种方法,您会生成一个固定的状态值,这可能对某些用例有效。但一般来说,你会想使用一个函数。

【讨论】:

    【解决方案2】:

    首先,您需要知道它们是什么?

    () => [] 是一个 arrow function,它返回一个空数组,但 [] 只是一个空数组。


    查看文档的note:

    reducers(Object):一个对象,其值对应不同的reduce函数,需要合并为一个。

    因此,您需要在 reducer 中传递一个函数。所以你将使用() => [] 而不是[]


    我从未在 combineReducers 中使用过此类。这用于组合不同的减速器,例如:

    combineReducers({
      reducer1,
      reducer2
    })
    

    前面的例子只是一个别名:

    combineReducers({
      reducer1: reducer1,
      reducer2: reducer2
    })
    

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 1970-01-01
      • 2012-02-21
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2018-10-21
      • 2020-07-11
      相关资源
      最近更新 更多