createSelector(...)和()=> createSelector(...)之间的区别

时间:2019-02-13 09:16:34

标签: reactjs select redux reselect

谁能告诉我这两种重新选择器用法之间的区别,并告诉我何时使用哪种选择器?

// First type of selector, without arrow function
export const selectMyValue = createSelector(
  rootSelector,
  state => state.get('someValue'),
)

// Second type of selector, with arrow function
export const selectMyValue = () => createSelector(
  rootSelector,
  state => state.get('someValue'),
)

2 个答案:

答案 0 :(得分:2)

  

这两种类型之间的差异

第一个示例将selectMyValue分配给返回的createSelector。因此,您可以使用您的状态来调用它:

const value = selectMyValue(someState)

第二个示例返回一个包装 createSelector的函数。但是createSelector尚未被调用。您将在以后使用该函数进行调用:

const wrapped = selectMyValue();
const value = wrapped(someState);

或一个班轮:

const value = selectMyValue()(someState);

  

何时使用哪个?

在大多数情况下,您可能会使用第一个。但是,当您需要为包装函数提供一些参数时,可能会出现这种情况。

例如:

export const selectMyValue = (value) => createSelector(
  rootSelector,
  state => state[value] // just an example
)

在这里,您的包装器接受一个名为value的参数。您可以将其称为实用程序以提取状态的不同部分:

const valueFromState = selectMyValue('someValue')(state);
const someOtherValueFromState = selectMyValue('someOtherValue')(state);

答案 1 :(得分:0)

第一个是一个简单选择器,可由您的应用程序直接使用,例如:

selectMyValue(state);

第二个是一个selector factory,换句话说,一个函数会在每次调用时返回一个全新的选择器实例。

const selectMyValue1 = selectMyValueFactory();
const selectMyValue2 = selectMyValueFactory();

// Calls to the following selectors won't invalidate each other's cache
selectMyValue1(state);
selectMyValue2(state);
相关问题