转载注:javascript
- 本文做者是淘宝前端团队的叶斋。笔者很是喜欢这篇文章,故从新排版并转载到这里,同时也加入了一些本身的体会。
- 原文地址:http://taobaofed.org/blog/201...
Redux 是「React 全家桶」中极为重要的一员,它试图为 React 应用提供「可预测化的状态管理」机制。Redux 自己足够简单,除了 React,它还可以支持其余界面框架。因此若是要将 Redux 和 React 结合起来使用,就还须要一些额外的工具,其中最重要的莫过于 react-redux 了。html
react-redux 提供了两个重要的对象,Provider
和connect
,前者使React
组件可被链接(connectable),后者把 React 组件和 Redux 的 store 真正链接起来。react-redux 的文档中,对connect
的描述是一段晦涩难懂的英文,在初学 redux 的时候,我对着这段文档阅读了好久,都没有所有弄明白其中的意思(大概就是,单词我都认识,连起来啥意思就不明白了的感受吧)。前端
在使用了一段时间 redux 后,本文尝试再次回到这里,给这段文档一个靠谱的解读。java
首先回顾一下 redux 的基本用法。若是你尚未阅读过 redux 的文档,你必定要先去阅读一下。react
const reducer = (state = {count: 0}, action) => { switch (action.type){ case 'INCREASE': return {count: state.count + 1}; case 'DECREASE': return {count: state.count - 1}; default: return state; } } const actions = { increase: () => ({type: 'INCREASE'}), decrease: () => ({type: 'DECREASE'}) } const store = createStore(reducer); store.subscribe(() => console.log(store.getState()) ); store.dispatch(actions.increase()) // {count: 1} store.dispatch(actions.increase()) // {count: 2} store.dispatch(actions.increase()) // {count: 3}
经过reducer
建立一个store
,每当咱们在store
上dispatch
一个action
,store
内的数据就会相应地发生变化。git
咱们固然能够直接在 React 中使用 Redux:在最外层容器组件中初始化store
,而后将state
上的属性做为props
层层传递下去。github
class App extends Component{ componentWillMount(){ store.subscribe((state)=>this.setState(state)) } render(){ return ( <Comp state={this.state} onIncrease={()=>store.dispatch(actions.increase())} onDecrease={()=>store.dispatch(actions.decrease())} /> ) } }
转载注:redux
- 另外一种方法,在入口文件
index.js
中初始化store
,并将其export
出来,而后import
到定义组件的文件中去。
但这并非最佳的方式。最佳的方式是使用 react-redux 提供的Provider
和connect
方法。api
首先在最外层容器中,把全部内容包裹在Provider
组件中,将以前建立的store
做为prop
传给Provider
。框架
const App = () => { return ( <Provider store={store}> <Comp/> </Provider> ) };
Provider
内的任何一个组件(好比这里的Comp
),若是须要使用state
中的数据,就必须是「被 connect 过的」组件——使用connect
方法对「你编写的组件(MyComp
)」进行包装后的产物。
class MyComp extends Component { // content... } const Comp = connect(...args)(MyComp);
可见,connect
方法是重中之重。
究竟connect
方法到底作了什么,咱们来一探究竟。
首先看下函数的签名:
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
connect()
接收四个参数,它们分别是mapStateToProps
,mapDispatchToProps
,mergeProps
和options
。
mapStateToProps(state, ownProps) : stateProps
这个函数容许咱们将store
中的数据做为props
绑定到组件上。
const mapStateToProps = (state) => { return { count: state.count } }
这个函数的第一个参数就是 Redux 的store
,咱们从中摘取了count
属性。由于返回了具备count
属性的对象,因此MyComp
会有名为count
的props
字段。
class MyComp extends Component { render(){ return <div>计数:{this.props.count}次</div> } } const Comp = connect(...args)(MyComp);
固然,你没必要将state
中的数据原封不动地传入组件,能够根据state
中的数据,动态地输出组件须要的(最小)属性。
const mapStateToProps = (state) => { return { greaterThanFive: state.count > 5 } }
函数的第二个参数ownProps
,是MyComp
本身的props
。有的时候,ownProps
也会对其产生影响。好比,当你在store
中维护了一个用户列表,而你的组件MyComp
只关心一个用户(经过props
中的userId
体现)。
const mapStateToProps = (state, ownProps) => { // state 是 {userList: [{id: 0, name: '王二'}]} return { user: _.find(state.userList, {id: ownProps.userId}) } } class MyComp extends Component { static PropTypes = { userId: PropTypes.string.isRequired, user: PropTypes.object }; render(){ return <div>用户名:{this.props.user.name}</div> } } const Comp = connect(mapStateToProps)(MyComp);
当state
变化,或者ownProps
变化的时候,mapStateToProps
都会被调用,计算出一个新的stateProps
,(在与ownProps
merge 后)更新给MyComp
。
这就是将 Redux store
中的数据链接到组件的基本方式。
转载注:
- 什么叫作“
MyComp
本身的props
”?假设在不使用 react-redux 的时候,MyComp
的父组件是ParentComp
,那么上文中的ownProps
是ParentComp
传递给MyComp
的所有属性(对于下文中的方法mapDispatchToProps
亦同)。也就是说,ownProps
与 Redux 的store
与state
彻底无关。- 方法
mapStateToProps
为MyComp
添加的属性,不可能被方法mapDispatchToProps
访问到,反之亦然。由于,这涉及到 render 的时机和顺序的问题,笔者在这上面踩过至关多的坑。至于笔者为何有这种需求,由于笔者设计了一个按钮,功能是:在点击后,根据当前的 state 计算出下一个 state,并更新。在经历了无数error
之后,笔者终于意识到:react-redux 根本就不是设计用来解决这类问题的。解决方案有两种:一是,在设计 reducer 的时候,就直接根据 state 更新;二是,导入全局store
并使用store.getState()
得到当前state
,而后根据这个state
进行更新。- 另外,若是使用PropTypes对
MyComp
作属性类型检查,方法mapStateToProps
和方法mapDispatchToProps
为MyComp
添加的属性是存在的。
mapDispatchToProps(dispatch, ownProps): dispatchProps
connect 的第二个参数是mapDispatchToProps
,它的功能是,将action
做为props
绑定到MyComp
上。
const mapDispatchToProps = (dispatch, ownProps) => { return { increase: (...args) => dispatch(actions.increase(...args)), decrease: (...args) => dispatch(actions.decrease(...args)) } } class MyComp extends Component { render(){ const {count, increase, decrease} = this.props; return (<div> <div>计数:{this.props.count}次</div> <button onClick={increase}>增长</button> <button onClick={decrease}>减小</button> </div>) } } const Comp = connect(mapStateToProps, mapDispatchToProps)(MyComp);
因为mapDispatchToProps
方法返回了具备increase
属性和decrease
属性的对象,这两个属性也会成为MyComp
的props
。
如上所示,调用actions.increase()
只能获得一个action
对象{type:'INCREASE'}
,要触发这个action
必须在store
上调用dispatch
方法。dispatch
正是mapDispatchToProps
的第一个参数。可是,为了避免让 MyComp 组件感知到dispatch
的存在,咱们须要将increase
和decrease
两个函数包装一下,使之成为直接可被调用的函数(即,调用该方法就会触发dispatch
)。
Redux 自己提供了bindActionCreators
函数,来将action
包装成直接可被调用的函数。
import {bindActionCreators} from 'redux'; const mapDispatchToProps = (dispatch, ownProps) => { return bindActionCreators({ increase: action.increase, decrease: action.decrease }); }
一样,当ownProps
变化的时候,该函数也会被调用,生成一个新的dispatchProps
,(在与stateProps
和ownProps
merge 后)更新给MyComp
。注意,action
的变化不会引发上述过程,默认action
在组件的生命周期中是固定的。
转载注:
- 函数
connect
甚至react-redux
的核心在于:将 Redux 中 store 的 state 绑定到组件的属性上,使得对 state 的修改可以直接体现为组件外观的更改。所以,参数mapStateToProps
是很是重要的,可是参数mapDispatchToProps
则比较多余——由于简单粗暴地导入全局 store 一样能达到相同的目的(事实上笔者就是这么作的)。
[mergeProps(stateProps, dispatchProps, ownProps): props]
以前说过,不论是stateProps
仍是dispatchProps
,都须要和ownProps
merge 以后才会被赋给MyComp
。connect
的第三个参数就是用来作这件事。一般状况下,你能够不传这个参数,connect
就会使用Object.assign
替代该方法。
最后还有一个options
选项,比较简单,基本上也不大会用到(尤为是你遵循了其余的一些 React 的「最佳实践」的时候),本文就略过了。但愿了解的同窗能够直接看文档。
(完)