我正在学习重新选择的用法,但我对使用容器内的记忆选择器的方式感到困惑。
我有一个名为的组件Summary
,它收到了 3 个道具subtotal, tipAmount , total
。
看起来像这样export const Summary = ({ subtotal = 0, tipAmount = 0, total = 0 })=>{...}
。这些道具正在将我的连接注入到我用以下代码调用HOC
的专用设备中。container
SummaryContainer
import { connect } from 'react-redux';
import { Summary } from '../components/Summary';
import {
selectTipAmount,
selectSubtotal,
selectTotal
} from '../store/items/selectors';
const mapStateToProps = (state) => {
const subtotal = selectSubtotal(state);
const tipAmount = selectTipAmount(state);
const total = selectTotal(state);
return {
subtotal,
tipAmount,
total
};
};
export const SummaryContainer = connect(mapStateToProps)(Summary);
如您所见,此代码使用 3 个选择器selectTipAmount
,selectSubtotal
并且selectTotal
我正在使用以下代码从选择器文件中导入。
import { createSelector } from 'reselect';
const selectItems = (state) => state.items;
const selectTipPercentage = (state) => state.tipPercentage;
export const selectSubtotal = createSelector([selectItems], (items) =>
items.reduce((acc, { price, quantity }) => acc + price * quantity, 0)
);
export const selectTipAmount = createSelector(
[selectSubtotal, selectTipPercentage],
(subtotal, tipPercentage) => subtotal * (tipPercentage / 100)
);
export const selectTotal = createSelector(
[selectSubtotal, selectTipAmount],
(subtotal, tipAmount) => subtotal + tipAmount
);
export const selectItemWithTotal = createSelector([selectItems], (items) =>
items.map((item) => ({ ...item, total: item.price * item.quantity }))
);
export const selectItem = (state, props) =>
state.items.find((item) => item.uuid === props.uuid);
export const selectItemTotal = createSelector(
[selectItem],
(item) => item.price * item.quantity
);
所以这是我的问题:
const total = selectTotal(state);
当我在里面调用 write时,mapStateToProps
我将执行的结果传递给total
常量,selectTotal(state) selector
当我查看 时argument
,它是 。state
看起来我正在selectTotal selector
通过传递和state
参数调用需要一个state param
。在实际实现中,选择等于这样的结果createSelect function
:
export const selectTotal = createSelector(
[selectSubtotal, selectTipAmount],
(subtotal, tipAmount) => subtotal + tipAmount
);
我还没有看到状态在哪里argument
通过。这是怎么回事?
该代码运行良好,但我不知道该state
参数的使用位置。
当我看selectItems selector
它时,它是有道理的,但是用我创建的选择器createSelector
我迷路了。