我真的不明白重新选择如何减少组件的渲染。这是我没有重新选择的:
const getListOfSomething = (state) => (
state.first.list[state.second.activeRecord]
);
const mapStateToProps = (state, ownProps) => {
console.log(state.first.list, state.second.activeRecord);
return {
...ownProps,
listOfSomething: getListOfSomething(state)
}
};
它根据某个值从某个列表中组合一个元素。每次状态发生变化时都会调用渲染,例如我的console.log
输出:
{}, ""
{}, ""
{}, ""
{}, "1"
{"filled", "1"}
因为商店的不同部分正在发生一些事情。因此,该组件被渲染了 5 次,其中 2 次是冗余的。
但是使用重新选择:
const getList = state => state.first.list;
const getActiveRecord = state => state.second.activeRecord;
const listOfSomething = (list, activeRecord) => {
console.log(list, activeRecord);
return list[activeRecord];
}
const getListOfSomething = createSelector(getList, getActiveRecord, listOfSomething);
const mapStateToProps = (state, ownProps) => {
console.log(state.first.list, state.second.activeRecord);
return {
...ownProps,
listOfSomething: getListOfSomething(state)
}
};
这是我的第一个选择器console.log
输出:
{}, ""
{}, "1"
{"filled", "1"}
第二:
{}, ""
{}, ""
{}, ""
{}, "1"
{"filled", "1"}
并且组件被正确渲染 - 3次!
为什么呢?为什么组件只渲染了 3 次?这里到底发生了什么?