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

  • 相关阅读:
    ZMQ面面观
    windows10系统右键新建菜单的自定义
    元组,列表,字典前加*
    HTTP状态码(转)
    字符串利用%02d将月份前加0
    python中while与else的联姻
    sys.argv
    pandas的read_csv踩到的坑
    wireshark抓包总结
    bcolz
  • 原文地址:https://www.cnblogs.com/taoquns/p/12036192.html
Copyright © 2011-2022 走看看