参考:https://segmentfault.com/a/1190000015042646
https://www.jianshu.com/p/e3cdce986ee2
https://segmentfault.com/a/1190000010416732?utm_source=tag-newest
- 介绍
React-Redux
是Redux
的官方React
绑定库。它能够使你的React
组件从Redux store
中读取数据,并且向store
分发actions
以更新数据。react-redux仅有2个API,Provider和connect,Provider提供的是一个顶层容器的作用,实现store的上下文传递。
connect方法比较复杂,虽然代码只有368行,但是为redux中常用的功能实现了和react连接的建立。
- API介绍
- conncet([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
conncet连接React组件与 Redux store, 实现了redux中常用的功能和react连接的建立。import {connect} from 'react-redux'; const mapState = (state) => ({ username: state.getIn(['header', 'user_info', 'user']), }); const mapDispatch = (dispatch) => ({ getUserList() { dispatch(actionCreators.actionGetUserList()); } }); export default connect(mapState, mapDispatch,[mergeProps], [options])(App);
参数介绍:
- mapStateToProps(state, ownProps)
这个函数允许我们将store
中的数据作为props
绑定到组件上。
这个函数的第一个参数就是 Redux 的store。
这个函数的第二个参数ownProps
,是当前组件自己的props。
const mapStateToProps = (state, ownProps) => { return { greaterThanFive: state.count > 5, id: ownProps.userId } }
- mapDispatchToProps(dispatch, ownProps)
它的功能是,将action
作为props
绑定到当前组件上。const mapDispatch = (dispatch, ownProps) => ({ getUserList1() { dispatch(actionCreators.actionGetUserList1()); },
getUserList2() { dispatch(ownProps.actionGetUserList2()); }
});
- mergeProps
mergeProps如果不指定,则默认返回 Object.assign({}, ownProps, stateProps, dispatchProps),顾名思义,mergeProps是合并的意思,将state合并后传递给组件。 - options
- mapStateToProps(state, ownProps)
- <Provider>
Provider提供的是一个顶层容器的作用,实现store的上下文传递。import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import route from './config/router'; //路由配置 import store from './store'; ReactDOM.render( <Provider store={store}> {route} </Provider> , document.getElementById('root') );
- conncet([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])