zoukankan      html  css  js  c++  java
  • Redux学习笔记-React-Redux 的用法

    参考:https://segmentfault.com/a/1190000015042646

             https://www.jianshu.com/p/e3cdce986ee2
             https://segmentfault.com/a/1190000010416732?utm_source=tag-newest

    • 介绍
      React-ReduxRedux的官方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
      • <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')
        );
  • 相关阅读:
    写日志文件
    内存文件映射应用举例『转』
    HOOK编程
    获取当前进程的名称
    C++实现FTP文件传输
    C/C++ 实现windows进程/线程/模块 遍历
    Unicode下的CString与char *转换
    MFC常用基本数据类型
    geos 3.6.1编译 win7 vs2015
    JQuery Mobile iscroll插件使用教程及注意事项
  • 原文地址:https://www.cnblogs.com/dadouF4/p/10536432.html
Copyright © 2011-2022 走看看