也许这不一定是一个重新选择的问题
const makeSelectError = () => createSelector(
selectGlobal,
(globalState) => globalState.get('error')
);
并重新选择我们使用
const mapStateToProps = createStructuredSelector({
error: makeSelectError(),
});
为什么我们不能像下面这样使用?
const makeSelectError = createSelector(
selectGlobal,
(globalState) => globalState.get('error')
);
并在重新选择中使用如下所示
const mapStateToProps = createStructuredSelector({
error: makeSelectError,
});
我的代码是否有任何问题/缺点,或者是标准做法?
答案 0 :(得分:2)
第二种方式不仅有效且正确,还有其它优点。
使用您提供的第一个代码段:
const makeSelectError = () => createSelector(
selectGlobal,
(globalState) => globalState.get('error')
);
makeSelectError
是一个工厂函数,因为每次调用它都会返回一个新的唯一选择器。
这意味着每次调用一个简单的mapStateToProps
函数时,都会生成一个新的选择器,并且将再次计算选择器的结果。
这意味着您将失去记忆化reselect
的主要优势。
因此,对于简单的情况,您可以执行以下操作:
const getSomePieceOfState = state => state.someArea.someDetail;
const getAnotherPieceOfState = state => state.anotherArea.anotherItem;
const getSomeCombinedState = createSelector(
getSomePieceOfState,
getAnotherPieceOfState,
(somePiece, anotherPiece) => somePiece + anotherPiece
);
const mapStateToProps = state => ({
someProp: getSomeCombinedState(state)
});
请注意。通过get
为选择器名称添加前缀并将makeGet
选择器工厂的名称(返回选择器的函数)作为前缀,这是很常见的。
有时候创建选择器工厂是必要的,但是如果你不想创建一个依赖于不在状态的属性的选择器。
您可以在此处详细了解Accessing React Props in Selectors
答案 1 :(得分:1)
你在第二个例子中完全正确。这是一种标准做法。
没有必要将makeSelectError
包装到另一个函数。