I am looking ways to improve performance of my React application. After some searching, I look into Reselect. But I am not sure how the example有效。
在该示例中,它指出每次更新组件时会计算todos
,从而影响性能。所以它介绍了使用memoized选择器来克服它。
如果我将getVisibleTodos
放在组件render
函数中,会有区别吗?我想做的是:
containers/VisibleTodoList.js
import React from 'react'
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed)
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed)
}
}
/*const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}*/
const mapStateToProps = (state) => {
return {
todos: state.todos,
visibilityFilter: state.visibilityFilter
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = ({todos, visibilityFilter, ...props}) => {
const visibleTodos = getVisibleTodos(todos, visibilityFilter);
return (
<TodoList todos={visibleTodos} {...props} />
)
}
const ConnectedVisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(VisibleTodoList)
export default ConnectedVisibleTodoList
在这种情况下,除非getVisibleTodos
或todos
更改,否则不会调用visibilityFilter
。对?我的修改是否与选择器一样?我错过了什么吗?
答案 0 :(得分:2)
不,getVisibleTodos
仍会被调用,并会在VisibleTodoList
重新呈现时重新计算。
VisibleTodoList
由connect
的react-redux包装,react-redux已为您提供了shouldComponentUpdate
。
但即使您使用shouldComponentUpdate
或connect
,它仍然没有像Reselect那样优化。因为当您在All,Active或Completed选项卡之间切换时,将调用getVisibleTodos
并且会有大量重复的重新计算。 (重新选择缓存这些结果,因此没有重复的重新计算)