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 )
    
    
  • 相关阅读:
    谷歌眼镜--参考文档
    谷歌眼镜--与菜单项互动
    谷歌眼镜--UI指南
    【cl】工程导入
    Ylmf_Ghost_Win7_SP1_x64_2017_0113.iso虚拟机安装
    win7_64
    linux下安装jdk
    rar x 解压rar文件,提示permission denied
    linux下安装rar解压包
    Red Hat Linux虚拟机与主机共享文件
  • 原文地址:https://www.cnblogs.com/taoquns/p/11936512.html
Copyright © 2011-2022 走看看