有2种方案:javascript
曾经,咱们会使用connect创建react和redux的通讯,例如,在一个class写法的组件中:java
import React from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import globalAction from 'actions/global' @connect( // 取得reducer中的state state => ({global: state.global}), // 取得action dispatch => bindActionCreators({ globalAction }, dispatch) ) class Component extends React.Component { componentDidMount() { // 从props中读取reducer和action const {global, globalAction} = this.props globalAction() console.log(global) } render() { return <div /> } }
对于用习惯了class组件的开发者来讲,这种写法烂熟于心了。可是,无论你多喜欢这种模式,仍是得学习react hook。react
随着react16.8的发布,hook功能正式投入使用。
将react的class组件转换成函数式组件,想必你已经看过官网的demo了,若是没看,回头看一下也不晚。那么,若是咱们使用了hook,又该如何跟redux通讯呢?
针对于这个问题,业界有人提供了一个取代react-redux的新插件redux-react-hook。
redux-react-hook使用了react提供的Context(上下文)功能,给顶层组件Provide传入了store对象,绑定到上下文。
使用了redux-react-hook以后,上面的demo就变成了下面这种写法:编程
import React, { useEffect } from 'react' import { useDispatch, useMappedState, StoreContext } from 'redux-react-hook' import globalAction from 'actions/global' function Component { // 获取上下文的store对象 const store = useContext(StoreContext) // 从store中读取reducer const {global} = store // 从store中读取dispatch const dispatch = useDispatch() useEffect(() => { dispatch(globalAction()) console.log(global) }, [global, dispatch, globalAction]) render() { return <div /> } }
修改后的demo使用到了redux-react-hook提供的其中2个API,StoreContext和useDispatch,其次,还能够使用useMappedState来获取reducer中的状态。redux
const mapState = useCallback( state => ({ global: state.global }), [], ); const { global } = useMappedState(mapState);
简单介绍写3个API,StoreContext,useDispatch,useMappedState。app
React提供的createContext建立上下文,返回该对象。ide
import { createContext } from 'react'; // 建立context const StoreContext = createContext<TStore | null>(null) return StoreContext
读取StoreContext,返回dispatch。函数式编程
function useDispatch(): Dispatch<TAction> { // 从上下文读取store const store = useContext(StoreContext); if (!store) { // store不存在,抛出异常 throw new MissingProviderError(); } return store.dispatch; } return useDispatch
useMappedState跟其余2个API不太同样,它是一个自定义的hook,用来订阅reducer里的状态。函数
hook式的写法到底是好是坏,暂且没法分辨,就像有人以为函数式编程很好,但有人以为函数式编程使得代码难于维护。
能够预见的是,当你使用了hook,会在项目中逐渐把class消灭,最后跟class语法糖告别,回归函数的世界。学习