Redux是[React全家桶]中极为重要的一员,它试图为React 应用提供[可预测化的状态管理]机制。Redux本身足够简单,除了React,它还能够支持其他界面框架。所以如果要将Redux和React 结合起来使用,就还需要一些额外的工具,其中最重要的莫过于react-
redux了。
react-redux提供了两个重要的对象,Provider和
connect
,前者使React 组件可被连接(connectable),后者把 React 组件和Redux的store真正连接起来。react-redux的文档中,对
connect的描述是一段晦涩难懂的英文,在初学redux的时候,我对着这段文档阅读了很久,都没有全部弄明白其中的意思(大概就是,单词我都认识,连起来啥意思就不明白了的感觉吧)。
在使用了一段时间redux后,本文尝试再次回到这里,给这段文档(同时摘抄在附录中)一个靠谱的解读。
预备知识
首先回顾一下redux的基本用法。如果你还没有阅读过redux的文档,你一定要先去阅读一下。
const reducer=(state=count:O),action)=>{
switch(action.type){
case'INCREASE':return{count:state.count+1);case'DECREASE':return(count:state.count-1);default:return state;const actions={
increase:0=>(type:INCREASE),decrease:0=>(type:'DECREASE'})
const store=createStore(reducer);store.subscribe(0=>
console.log(store.getState0)
store.dispatch(actions.increase0)//{count:1}store.dispatch(actions.increase0)//{count:2}store.dispatch(actions.increase0)//{count:3}
通过
reducer创建一个
store
,每当我们在
store dispatch一个
action store内的数据就会相应地发生变化。
我们当然可以直接在React中使用Redux:在最外层容器组件中初始化store
,然后将
state上的属性作为
props层层传递下去。
class App extends Component{
componentWillMountO{
store.subscribe((state)=>this.setState(state)
render0{
return <Comp state={this.state}
onlncrease={0=>store.dispatch(actions.increase0}
onDecrease={0=>store.dispatch(actions.decrease0)}
但这并不是最佳的方式。最佳的方式是使用react-redux提供的Provider和
connect方法。