如何在一条语句中从 Redux 存储中获取多个值?

How can I get more than one value from the Redux store in a single statement?

我有这个代码:

const { user } = useSelector((state) => state.userReducer);
const { other } = useSelector((state) => state.otherReducer);

我如何在一行中从商店中获取这两个(或更多)值?

const { user, other } = useSelector((state) => ?);

嗯,原来是:

  const { userReducer: { user }, otherReducer: { other } } = useSelector((state) => state);
const { user, other } = useSelector((state) => ({ 
  user: state.userReducer,
  other: state.otherReducer
}))

如果你使用 lodash:

import { pick, isEqual } from 'lodash-es';

const { userReducer, otherReducer } = useSelector(
  (state) => pick(state, ['userReducer', 'otherReducer']), 
  isEqual
)

第二个参数(isEqual)旨在解决@NicholasTower提到的潜在性能问题(相当于react-reduxshallowEqual)。
如果没有浅对象相等函数,组件将 re-render 每次 any 突变提交到该存储,无论键如何。

在一行中完成它的天真的方法是编写一个函数来获取您关心的部分状态,并构造一个具有这些属性的对象:

const { user, other } = useSelector((state) => {
  return { user: state.userReducer, other: state.otherReducer };
});

但是,这会立即导致性能问题。选择器每次运行时,都会创建一个全新的对象。即使 userother 没有改变,外部对象 已经 改变,所以你的组件被迫重新渲染。换句话说,每次在应用程序中的任何位置调度任何操作时,您的组件都会重新呈现。

为了解决这个问题,useSelector 允许您提供一个额外的函数来定义两个值是否相等。然后你可以实现一个函数来检查你关心的东西是否发生了变化:

const { user, other } = useSelector((state) => {
  return { user: state.userReducer, other: state.otherReducer };
}, (a, b) => {
  return a.user === b.user && a.other === b.other
});

react-redux 带有浅比较功能,如果您愿意,它可能对这个目的有用:

import { useSelector, shallowEqual } from 'react-redux';
// ...

const { user, other } = useSelector((state) => {
  return { user: state.userReducer, other: state.otherReducer };
}, shallowEqual);

建议使用数组而不是对象以避免重复键

const [user, other] = useSelector(state => [state.userReducer, state.otherReducer])