美文网首页React Native
伟哥带你玩Redux

伟哥带你玩Redux

作者: 踏云小子 | 来源:发表于2017-11-22 16:24 被阅读19次

    Redux有点类似信号编程,只需关注信号的发射和监听

    四个要素

    1.Store

    • 定义
      存储数据的对象,一个应用只有一个store

    • 如何创建

    import { createStore } from 'redux'
    const store = createStore(fn)
    

    2.State

    • 定义
      一个时间点对应一个快照,state与view相关联,state变化导致view变化

    • 如何获取

    const state = store.getState();
    

    3.Action

    • 定义
      View通过action来使state变化,View -(Action)->State

    • 如何创建

    const action = {
      type: 'ADD_INFO',//action的名称
      data//action附加的信息
    }
    

    4.Reducer

    • 定义
      state变化的规则

    四个步骤

    • 定义reducer
    • 创建store
    • 订阅
    • 触发action

    Redux在React中的应用

    1.前戏:设计一个文件夹目录

    · redux
      · actions
      · store
      · reducers
    

    2.小试牛刀:state的展示与修改

    3.正式实战:

    3.1单个页面,共用一个redux
    3.2多个页面,共用一个redux
    Detail.jsx
    
    import { connect } from 'react-redux'
    import { bindActionCreators } from 'redux'
    import * as userinfoActions from '../../redux/actions/userinfo'
    
    // 任何时候,只要 Redux store 发生改变,mapStateToProps 函数就会被调用
    function mapStateToProps(state) {
      return {
        haha: state.userinfo
      }
    }
    
    function mapDispatchToProps(dispatch) {
      return {
        userinfoActions: bindActionCreators(userinfoActions, dispatch)
      }
    }
    
    export default connect(
        mapStateToProps,
        mapDispatchToProps
    )(Detail);
    
    //this.props.haha.userid以及this.props.haha.city就可以拿到了
    

    相关文章

      网友评论

        本文标题:伟哥带你玩Redux

        本文链接:https://www.haomeiwen.com/subject/uaiduxtx.html