【发布时间】: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