zoukankan      html  css  js  c++  java
  • react 添加 react-redux 基本用法

    安装

    yarn add react-redux
    

    创建文件、文件夹

    |- redux
      |- actions.js
      |- reducer.js
      |- store.js
    

    actions.js

    
    export const change_user_info = "changeUserInfo"
    
    export function ChangeUserInfo( data ){
      return {
        type: change_user_info,
        data: data
      }
    }
    

    reducer.js

    import { change_user_info } from "./actions"
    
    let storeState = {
      userInfo: null
    }
    
    export default function Store( state = storeState, actions ){
    
        switch( actions.type ){
            case change_user_info:
                return { ...state, userInfo: actions.data  }
            default:
                return state
        }
    }
    

    store.js

    import { createStore } from 'redux'
    import reducer from './reducer'
    const store = createStore(reducer)
    export default store
    

    引入

    import { Provider } from "react-redux"
    import store from "./redux/index"
    
    ReactDOM.render( 
        <Provider store={ store } >
            <App/>
        </Provider>, 
        document.getElementById('root')
    );
    

    使用

    // 在组件内 引入
    import * as React from "react"
    import { connect } from "react-redux"
    import { changeUserInfo } from "@/redux/actions"
    
    class Hello extends React.Component{ 
      
      // 使用方式
      // this.props.userInfo
      // this.props.changeUserInfo( data )
      ...
      // 省略
    }
    
    const mapStateToProps = ( state ) =>{
        return {
            userInfo: state.userInfo
        }
    }
    
    const mapActionsToProps = ( dispatch )=>{
        return {
            changeUserInfo: ( data )=>{
                dispatch( changeUserInfo( data ) )
            }
        }
    }
    
    export default connect( mapStateToProps, mapActionsToProps )( Hello )
    
    

    作者:taoqun
    地址:http://taoquns.com/paper/46

  • 相关阅读:
    回流和重绘
    php 异常捕获的坑
    每周散记 20180806
    转: Linux mount/unmount命令
    python http 请求 响应 post表单提交
    每周散记 20180723
    优惠劵产品分析
    c++ 软件版本比较函数
    每周散记
    转: 系统问题排查思路
  • 原文地址:https://www.cnblogs.com/taoquns/p/12036192.html
Copyright © 2011-2022 走看看