Is Reselect really needed in the Todo List example in Redux?

时间:2017-03-23 04:03:53

标签: javascript reactjs redux reselect

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

在这种情况下,除非getVisibleTodostodos更改,否则不会调用visibilityFilter。对?我的修改是否与选择器一样?我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

不,getVisibleTodos仍会被调用,并会在VisibleTodoList重新呈现时重新计算。

<德尔> 此外,由于`VisibleTodoList`是一个功能组件,当它的父组件有更新时,它将每次重新呈现。 所以不,你的代码和Reselect表现不同。我想你想要的是一个类组件,并添加`shouldComponentUpdate`来手动比较`todos`和`visibilityFilter`,然后你可以避免不必要的计算。


VisibleTodoListconnect的react-redux包装,react-redux已为您提供了shouldComponentUpdate

但即使您使用shouldComponentUpdateconnect,它仍然没有像Reselect那样优化。因为当您在All,Active或Completed选项卡之间切换时,将调用getVisibleTodos并且会有大量重复的重新计算。 (重新选择缓存这些结果,因此没有重复的重新计算)