react 计算衍生数据
import React from 'react' import { connect } from 'react-redux' import TodoList from '../components/TodoList' import {toggleTodo,VisibilityFilters} from '../actions/index' import { createSelector } from 'reselect' const getVisibleTodos = (todos,filter)=>{ switch (filter) { case 'SHOW_ALL': return todos break; case 'SHOW_COMPLETED': return todos.filter((todo)=>todo.completed) break; case 'SHOW_ACTIVE': return todos.filter(t=>!t.completed) break; default: throw new Error('Unknown filter: ' + filter) } } const mapStateToProps = (state, ownProps) => { console.log(state) return { todos: getVisibleTodos(state.todos,state.visibilityFilter) } } const mapDispatchToProps = (dispatch, ownProps) => { return { toggleTodo: (id) => { dispatch(toggleTodo(id)) } } } export default connect(mapStateToProps,mapDispatchToProps)(TodoList)
从上面的例子可以看出每次组件更新时 todos列表都会被从新计算,如果 state tree 非常大,或者计算量非常大,每次更新都重新计算可能会带来性能问题。Reselect 能帮你省去这些没必要的重新计算。
import React from 'react' import { connect } from 'react-redux' import TodoList from '../components/TodoList' import {toggleTodo,VisibilityFilters} from '../actions/index' import { createSelector } from 'reselect' const getTodos = (state)=>state.todos; const visibilityFilter = (state)=>state.visibilityFilter //计算衍生数据
createSelector接受二个参数 第一个参数为input-select 意思是当那些状态变更时才会从新计算todos列表 是一个数组函数。
第二个参数是一个函数 参数是:将前一个参数的返回值作为参数
const getVisibleTodos = createSelector( [getTodos,visibilityFilter],(todos,filter)=>{ switch (filter) { case 'SHOW_ALL': return todos break; case 'SHOW_COMPLETED': return todos.filter((todo)=>todo.completed) break; case 'SHOW_ACTIVE': return todos.filter(t=>!t.completed) break; default: throw new Error('Unknown filter: ' + filter) } }) const mapStateToProps = (state, ownProps) => { console.log(state) return { // todos: getVisibleTodos(state.todos,state.visibilityFilter) todos:getVisibleTodos(state) } } const mapDispatchToProps = (dispatch, ownProps) => { return { toggleTodo: (id) => { dispatch(toggleTodo(id)) } } } export default connect(mapStateToProps,mapDispatchToProps)(TodoList)