关于react-redux中Provider、connect的解析

是什么

react-redux 提供的一个 React 组件

作用

把 store 提供给其子组件

  1. //使用 redux 的 createStore 方法创建的一个 store
  2. const store = createStore(todoApp,{})
  3. // store 作为一个 prop 传给 Provider 组件
  4. render(
  5. <Provider store={store}>
  6. <App/>
  7. </Provider>, document.getElementById('app'))

connect

  1. connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

作用

把“指定的state & 指定的action”和 React组件 连接起来 ==> 容器组件

参数说明

mapStateToProps

这是一个function,返回一个object;

(state, [ownProps]) => ({ }) // 通常省略第二个参数

作用 把指定的state作为props注入到 UI组件 中

  1. const mapStateToProps = state => {
  2. return {
  3. title: state.title,
  4. list: state.list
  5. };
  6. }

当然,不必将 state 中的数据原封不动地传入组件,可以根据 state 中的数据,动态地输出组件需要的(最小)属性。

  1. const mapStateToProps = (state) => {
  2. return {
  3. greaterThanFive: state.count > 5 // 假如只需要知道count大不大于5就成
  4. }
  5. }

函数的第二个参数 ownProps,是 React的UI组件自己的 props。有的时候,ownProps 也会对其产生影响。

比如,当你在 store 中维护了一个用户列表,而你的组件只关心一个用户。

  1. const mapStateToProps = (state, ownProps) => {
  2. // state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}
  3. return {
  4. user: _.find(state.userList, {id: ownProps.userId})
  5. }
  6. }
  7. class MyComp extends Component {
  8. static PropTypes = {
  9. userId: PropTypes.string.isRequired,
  10. user: PropTypes.object
  11. };
  12. render(){
  13. return <div>用户名:{this.props.user.name}</div>
  14. }
  15. }
  16. const Comp = connect(mapStateToProps)(MyComp);

mapDispatchToProps

这可以是一个function,还可以是object,

作用 把指定的action作为props注入到UI组件中

  1. // 方法
  2. const mapDispatchToProps = dispatch => {
  3. return {
  4. destroyTodo : () => dispatch({
  5. type : 'DESTROY_TODO'
  6. })
  7. }
  8. }
  9. // 对象

mergeProps

是一个函数,用来筛选哪些参数传递给组件。这个函数接受3个参数

  1. const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({
  2. ...ownProps,
  3. ...stateProps,
  4. ...dispatchProps
  5. })

stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是当前组件自己的属性。

这个函数默认把这三个返回值拼装到一起传递给组件,可修改。

options

一个对象,有两个布尔,一个是pure,一个是withRef。

  • pure为false,只要connect接受到属性,不管是否有变化,必然刷新connect组件。
  • withRef为true时,在装饰传入的 React 组件时,Connect 会保存一个对该组件的 refs 引用,可以通过 getWrappedInstance 方法来获得该 refs,并最终获得原始的 DOM 节点。

使用

  1. const newApp = connect(store)(UI)