【问题标题】:How to efficiently select a redux store slice如何高效选择一个redux store slice
【发布时间】:2021-06-19 09:33:11
【问题描述】:

在 React/Hooks/ReduxToolkit 应用程序中,通过以下两种方法选择 redux 存储的切片对效率有何影响:

商店结构:

常量存储:RootState = { 学生, 培训班, }

students 是由他们的id 索引的学生字典......即 学生:[id: number]:学生 同样,courses 是一个由他们的id 索引的课程字典

在只关心呈现student 信息的组件中,直接选择组件中的相关切片与创建组件然后调用的记忆选择器的性能影响是什么?

案例1(组件中直接选择切片):

const StudentReactComponent = () => {
const allStudents = useSelector((state: RootState) => state.students)

...
return some render logic that makes use of `allStudents`
...
}

案例 2(通过记忆选择器选择切片):

// This memoized selector would actually be imported from a `studentSelectors`
// module instead of being declared above the react component
const selectStudentsDictionary = createSelector((state: RootState) => state.students, students => students)

const StudentReactComponent = () => {
const allStudents = useSelector(selectStudentsDictionary)
...
return some render logic that makes use of `allStudents`
...

【问题讨论】:

  • 由于您在两种情况下都直接访问数据,因此第一种情况实际上会更快。如果您没有在每次渲染时生成新函数,但您是在比较选择器上的对象并存储结果。而不是直接访问数据。所以在这里找案例一。欲了解更多信息:kentcdodds.com/blog/usememo-and-usecallback

标签: reactjs redux react-hooks redux-toolkit reselect


【解决方案1】:

useSelector 在选择器返回不同于先前引用的新引用时强制组件重新渲染:https://react-redux.js.org/api/hooks#equality-comparisons-and-updates。因此,正如所写,只要state.students 发生变化,组件就会重新渲染。

这个例子中的“memoized”选择器实际上是没有用的。仅当您拥有派生数据时,记忆才重要。任何时候你有一个 createSelector 实例,它只有 x => x 作为它的“输出选择器”,你使用 createSelector 的方式是错误的,这可能只是一个普通的函数。

作为相关的附注,我实际上计划在不久的将来为 Redux 核心文档编写一个新的“选择器和记忆化”使用指南页面。在那之前,我建议通读我的帖子Using Reselect Selectors for Encapsulation and Performance。它已经有几年历史了,但在这里仍然很重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2016-03-03
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2017-12-19
    • 2017-09-17
    相关资源
    最近更新 更多