react-redux@7.1.0 useSelector: 别啦 connect

React-redux 7.1发版啦。react

API简单的介绍

由于在新的项目中用到了hooks,可是用的时候react-redux还处于alpha.x版本的状态。用不了最新的API,感受不是很美妙。好在,这两天发布了7.1版本。git

如今来看看怎么用这个新的API。github

useSelector()

const result : any = useSelector(selector : Function, equalityFn? : Function)
复制代码

这个是干啥的呢?就是从redux的store对象中提取数据(state)。redux

注意: 由于这个可能在任什么时候候执行屡次,因此你要保持这个selector是一个纯函数。api

这个selector方法相似于以前的connect的mapStateToProps参数的概念。而且useSelector会订阅store, 当action被dispatched的时候,会运行selector。数组

固然,仅仅是概念和mapStateToProps类似,可是确定有不一样的地方,看看selector和mapStateToProps的一些差别:缓存

  • selector会返回任何值做为结果,并不只仅是对象了。而后这个selector返回的结果,就会做为useSelector的返回结果。
  • 当action被dispatched的时候,useSelector()将对前一个selector结果值和当前结果值进行浅比较。若是不一样,那么就会被re-render。 反之亦然。
  • selector不会接收ownProps参数,可是,能够经过闭包(下面有示例)或使用柯里化selector来使用props。
  • 使用记忆(memoizing) selector时必须格外当心(下面有示例)。
  • useSelector()默认使用===(严格相等)进行相等性检查,而不是浅相等(==)。

你可能在一个组件内调用useSelector屡次,可是对useSelector()的每一个调用都会建立redux store的单个订阅。因为react-reduxv7版本使用的react的批量(batching)更新行为,形成同个组件中,屡次useSelector返回的值只会re-render一次。性能优化

相等比较和更新

当函数组件渲染时,会调用提供的selector函数,而且从useSelector返回其结果。(若是selector运行且没有更改,则会返回缓存的结果)。闭包

上面有说到,只当对比结果不一样的时候会被re-render。从v7.1.0-alpha.5开始,默认比较是严格比较(===)。这点于connect的时候不一样,connect使用的是浅比较。这对如何使用useSelector()有几个影响。jsp

使用mapState,全部单个属性都在组合对象中返回。返回的对象是不是新的引用并不重要 - connect()只比较各个字段。使用useSelector就不行了,默认状况下是,若是每次返回一个新对象将始终进行强制re-render。若是要从store中获取多个值,那你能够这样作:

  • useSelector()调用屡次,每次返回一个字段值。

  • 使用Reselect或相似的库建立一个记忆化(memoized) selector,它在一个对象中返回多个值,但只在其中一个值发生更改时才返回一个新对象。

  • 使用react-redux 提供的shallowEqual函数做为useSelectorequalityFn参数。

就像下面这样:

import { shallowEqual, useSelector } from 'react-redux'

// later
const selectedData = useSelector(selectorReturningObject, shallowEqual)
复制代码

useSelector 例子

上面作了一些基本的阐述,下面该用一些例子来加深理解。

基本用法

import React from 'react'
import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  const counter = useSelector(state => state.counter)
  return <div>{counter}</div>
}
复制代码

经过闭包使用props来肯定要提取的内容:

import React from 'react'
import { useSelector } from 'react-redux'

export const TodoListItem = props => {
  const todo = useSelector(state => state.todos[props.id])
  return <div>{todo.text}</div>
}
复制代码

使用记忆化(memoizing) selector

对于memoizing不是很了解的,能够通往此处了解。

当使用如上所示的带有内联selector的useSelector时,若是渲染组件,则会建立selector的新实例。只要selector不维护任何状态,这就能够工做。可是,记忆化(memoizing) selectors 具备内部状态,所以在使用它们时必须当心。

当selector仅依赖于状态时,只需确保它在组件外部声明,这样一来,每一个渲染所使用的都是相同的选择器实例:

import React from 'react'
import { useSelector } from 'react-redux'
import { createSelector } from 'reselect' //上面提到的reselect库

const selectNumOfDoneTodos = createSelector(
  state => state.todos,
  todos => todos.filter(todo => todo.isDone).length
)

export const DoneTodosCounter = () => {
  const NumOfDoneTodos = useSelector(selectNumOfDoneTodos)
  return <div>{NumOfDoneTodos}</div>
}

export const App = () => {
  return (
    <>
      <span>Number of done todos:</span>
      <DoneTodosCounter />
    </>
  )
}
复制代码

若是selector依赖于组件的props,可是只会在单个组件的单个实例中使用,则状况也是如此:

import React from 'react'
import { useSelector } from 'react-redux'
import { createSelector } from 'reselect'

const selectNumOfTodosWithIsDoneValue = createSelector(
  state => state.todos,
  (_, isDone) => isDone,
  (todos, isDone) => todos.filter(todo => todo.isDone === isDone).length
)

export const TodoCounterForIsDoneValue = ({ isDone }) => {
  const NumOfTodosWithIsDoneValue = useSelector(state =>
    selectNumOfTodosWithIsDoneValue(state, isDone)
  )

  return <div>{NumOfTodosWithIsDoneValue}</div>
}

export const App = () => {
  return (
    <>
      <span>Number of done todos:</span>
      <TodoCounterForIsDoneValue isDone={true} />
    </>
  )
}
复制代码

可是,若是selector被用于多个组件实例而且依赖组件的props,那么你须要确保每一个组件实例都有本身的selector实例(为何要这样?看这里):

import React, { useMemo } from 'react'
import { useSelector } from 'react-redux'
import { createSelector } from 'reselect'

const makeNumOfTodosWithIsDoneSelector = () =>
  createSelector(
    state => state.todos,
    (_, isDone) => isDone,
    (todos, isDone) => todos.filter(todo => todo.isDone === isDone).length
  )

export const TodoCounterForIsDoneValue = ({ isDone }) => {
  const selectNumOfTodosWithIsDone = useMemo(
    makeNumOfTodosWithIsDoneSelector,
    []
  )

  const numOfTodosWithIsDoneValue = useSelector(state =>
    selectNumOfTodosWithIsDoneValue(state, isDone)
  )

  return <div>{numOfTodosWithIsDoneValue}</div>
}

export const App = () => {
  return (
    <>
      <span>Number of done todos:</span>
      <TodoCounterForIsDoneValue isDone={true} />
      <span>Number of unfinished todos:</span>
      <TodoCounterForIsDoneValue isDone={false} />
    </>
  )
}
复制代码

useDispatch()

const dispatch = useDispatch()
复制代码

这个Hook返回Redux store中对dispatch函数的引用。你能够根据须要使用它。

用法和以前的同样,来看个例子:

import React from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()

  return (
    <div>
      <span>{value}</span>
      <button onClick={() => dispatch({ type: 'increment-counter' })}>
        Increment counter
      </button>
    </div>
  )
}
复制代码

当使用dispatch将回调传递给子组件时,建议使用useCallback对其进行记忆,不然子组件可能因为引用的更改进行没必要要地呈现。

import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()
  const incrementCounter = useCallback(
    () => dispatch({ type: 'increment-counter' }),
    [dispatch]
  )

  return (
    <div>
      <span>{value}</span>
      <MyIncrementButton onIncrement={incrementCounter} />
    </div>
  )
}

export const MyIncrementButton = React.memo(({ onIncrement }) => (
  <button onClick={onIncrement}>Increment counter</button>
))
复制代码

useStore()

const store = useStore()
复制代码

这个Hook返回redux <Provider>组件的store对象的引用。

这个钩子应该不长被使用。useSelector应该做为你的首选。可是,有时候也颇有用。来看个例子:

import React from 'react'
import { useStore } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const store = useStore()

  // 仅仅是个例子! 不要在你的应用中这样作.
  // 若是store中的state改变,这个将不会自动更新
  return <div>{store.getState()}</div>
}
复制代码

性能

前面说了,selector的值改变会形成re-render。可是这个与connect有些不一样,useSelector()不会阻止组件因为其父级re-render而re-render,即便组件的props没有更改。

若是须要进一步的性能优化,能够在React.memo()中包装函数组件:

const CounterComponent = ({ name }) => {
  const counter = useSelector(state => state.counter)
  return (
    <div>
      {name}: {counter}
    </div>
  )
}

export const MemoizedCounterComponent = React.memo(CounterComponent)
复制代码

Hooks 配方

配方: useActions()

这个是alpha的一个hook,可是在alpha.4中听取Dan的建议被移除了。这个建议是基于“binding actions creator”在基于钩子的用例中没啥特别的用处,而且致使了太多的概念开销和语法复杂性。

你可能更喜欢直接使用useDispatch。你可能也会使用Redux的bindActionCreators函数或者手动绑定他们,就像这样: const boundAddTodo = (text) => dispatch(addTodo(text))

可是,若是你仍然想本身使用这个钩子,这里有一个现成的版本,它支持将action creator做为单个函数、数组或对象传递进来。

import { bindActionCreators } from 'redux'
import { useDispatch } from 'react-redux'
import { useMemo } from 'react'

export function useActions(actions, deps) {
  const dispatch = useDispatch()
  return useMemo(() => {
    if (Array.isArray(actions)) {
      return actions.map(a => bindActionCreators(a, dispatch))
    }
    return bindActionCreators(actions, dispatch)
  }, deps ? [dispatch, ...deps] : deps)
}
复制代码

配方: useShallowEqualSelector()

import { shallowEqual } from 'react-redux'

export function useShallowEqualSelector(selector) {
  return useSelector(selector, shallowEqual)
}
复制代码

使用

如今在hooks组件里,咱们不须要写connect, 也不须要写mapStateToProps, 也不要写mapDispatchToProps了,只须要一个useSelector

问题

你们对于这个版本有没有感受不满意的地方?

原文:简书: react-redux@7.1的api,用于hooks

代码注释:v7.1 code

相关文章
相关标签/搜索