react中使用redux

1. 首先安装相关依赖
yarn add react-router-dom redux react-redux axios redux-logger redux-thunk -S or npm i xxxx -S
2. 创建Store文件夹及内部文件(index.js, reducer.js, actionCreator.js, actionType.js),以及utils文件夹下(api.js 和 http.js)
// index.js
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducer';

// 相关中间件
import thunk from 'redux-thunk';
import logger from 'redux-logger'

// redux 调试工具
const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;
const enhancer = composeEnhancers(
    applyMiddleware(thunk, logger)
);

const store = createStore(reducer, enhancer)

export default store;
// reducer.js
import * as actionType from './actionType'

const defaultState = {
    homeData: {}
}

export default (state = defaultState, action) => {
    console.log('reducer', state, action)
    let newState = JSON.parse(JSON.stringify(state))
    if (action.type === actionType.ININ_HOME_DATA) {
        newState.homeData = action.homeData
    }
    return newState
}
// actionType.js
export const ININ_HOME_DATA = 'inin_home_data'
// actionCreator.js
import * as actionType from './actionType'
import { getHomeData } from '../utils/api';

export const getHomeDataAction = () => {
    return (dispatch) => {
        getHomeData().then( res => {
            // console.log(res)
            if (res.code === 200) {
                dispatch({
                    type: actionType.ININ_HOME_DATA,
                    homeData: res.data
                })
            }else{
                console.log('err')
            }
        }).catch( err => {
            console.log(err)
        })
    }
}
// http.js
import axios from 'axios';

// get post 请求封装
export function get(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: param}).then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        }).catch((error) => {
            reject(error)
        })
    })
}

export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error)
        })
    })
}
// api.js
import { get } from './http'

// 你的域名
let rootUrl = 'http://192.168.0.125';

// 首页接口数据
export const getHomeData = () => get(rootUrl + '/api/home/content')
3. 连接redux到项目中,在index.js中连接
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

// 引入redux
import { Provider } from 'react-redux';
import store from './Store/index';

ReactDOM.render(
  
    
  ,
  document.getElementById('root')
);
4. 创建Router/routes.js文件
import Home from '../Pages/Home/Home.jsx'
import Login from '../Pages/Login/Login.jsx'

let routes = [
    {path: '/', component: Home, exact: true},
    {path: '/login', component: Login},
]

export default routes
5. App.js调用actionCreator方法
import React, { Component } from 'react';
import { connect } from 'react-redux';
// 引入路由
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import './App.css'
// 引入路由文件
import routes from './Router/routes'
// 调用 actionCreator 方法,调取接口数据
import { getHomeDataAction } from './Store/actionCreator'

// 动态路由设置
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {  }
  }
  render() { 
    let { homeData } = this.props
    return (
      
        
  • Home
  • Login
{ routes.map ((route, key) => { if(route.exact) { return ( ( )} /> ) }else{ return ( ( )} /> ) } }) }
); } componentDidMount() { this.props.reqHomeData() } } const mapStateToProps = (state) => { // console.log('app.js', state) return { homeData: state.homeData }; } const mapDispatchToProps = (dispatch) => { return { reqHomeData() { let action = getHomeDataAction() dispatch(action) } }; } export default connect(mapStateToProps, mapDispatchToProps)(App)
6. 依次写出login接口
//1.首先 api.js 填充 login 接口
export const postLoginData = (user, pwd) => post(rootUrl + `/api/sso/login?username=${user}&password=${pwd}`)
//2. actionCreator 编写登录函数
import { postLoginData } from '../utils/api';

export const postLoginDataAction = (user, pwd) => {
    return (dispatch) => {
        postLoginData(user, pwd).then( res => {
            // console.log('login', res)
            if (res.code === 200) {
                dispatch({
                    type: actionType.ININ_LOGIN_DATA,
                    loginData: res.data
                })
            }else{
                console.log('err')
            }
        }).catch( err => {
            console.log(err)
        })
    }
}
// 3.在 reducer.js 中进行判断
import * as actionType from './actionType'

const defaultState = {
    homeData: {},
    loginData: {}
}

export default (state = defaultState, action) => {
    // console.log('reducer', state, action)
    let newState = JSON.parse(JSON.stringify(state))
    if (action.type === actionType.ININ_HOME_DATA) {
        newState.homeData = action.homeData
    }else if(action.type === actionType.ININ_LOGIN_DATA) {
        newState.loginData = action.loginData
    }
    return newState
}

然后在login.jsx中调用接口

import react, { Component } from 'react';
import { connect } from 'react-redux';
import { postLoginDataAction } from '../../Store/actionCreator';

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '18888888888',
            password: '123456'
        }
    }
    changeName = (event) => {
        this.setState({
            username: event.target.value
        })
    }
    changepwd = (event) => {
        this.setState({
            password: event.target.value
        })
    }
    render() { 
        let { loginData } = this.props
        console.log('login page', loginData)
        return (
            

Login




); } login = () => { let { username, password } = this.state this.props.reqLoginData(username, password) } } const mapStateToProps = (state) => { return { loginData: state.loginData } } const mapDispatchToProps = (dispatch) => { return { reqLoginData(username, password) { let action = postLoginDataAction(username, password) dispatch(action) } } } export default connect(mapStateToProps, mapDispatchToProps)(Login);

你可能感兴趣的:(react中使用redux)