react和redux建立通信的方式
有2种方案:
老方案connect 新方案hook老方案connect
曾经,我们会使用connect建立react和redux的通信,例如,在一个class写法的中:
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 <p />
}
}
对于用习惯了class组件的开发者来说,这种写法烂熟于心了。但是,不管你多喜欢这种模式,还是得学习react hook。
新方案hook
随着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 <p />
}
}
修改后的demo使用到了redux-react-hook提供的其中2个api,storecontext和usedispatch,其次,还可以使用usemappedstate来获取reducer中的状态。
const mapstate = usecallback(
state => ({
global: state.global
}),
[],
);
const { global } = usemappedstate(mapstate);
redux-react-hook
简单介绍写3个api,storecontext,usedispatch,usemappedstate。
storecontext
react提供的createcontext创建上下文,返回该对象。
import { createcontext } from 'react';
// 创建context
const storecontext = createcontext<tstore | null>(null)
return storecontext
usedispatch
读取storecontext,返回dispatch。
function usedispatch(): dispatch<taction> {
// 从上下文读取store
const store = usecontext(storecontext);
if (!store) {
// store不存在,抛出异常
throw new missingprovidererror();
}
return store.dispatch;
}
return usedispatch
usemappedstate
usemappedstate跟其他2个api不太一样,它是一个自定义的hook,用来订阅reducer里的状态。
总结
hook式的写法究竟是好是坏,暂且无法分辨,就像有人觉得函数式很好,但有人觉得函数式编程使得代码难于维护。
可以预见的是,当你使用了hook,会在项目中逐渐把class消灭,最后跟class语法糖告别,回归函数的世界。
黄山小妖是我老婆