美文网首页
react中使用redux

react中使用redux

作者: 郭先生_515 | 来源:发表于2020-12-14 14:29 被阅读0次
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(
  <Provider store={store}>
    <App />
  </Provider>,
  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 (
      <Router>
        <ul className="topBar">
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        {
          routes.map ((route, key) => {
            if(route.exact) {
              return (
                <Route 
                  key = {key} 
                  exact
                  path = {route.path} 
                  render = {props => (
                    <route.component {...props} />
                  )}
                />
              )
            }else{
              return (
                <Route 
                  key = {key} 
                  path = {route.path} 
                  render = {props => (
                    <route.component {...props} />
                  )}
                />
              )
            }
          })
        }
      </Router>
    );
  }
  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 (
            <div>
                <h1>Login</h1>
                <input type="tel" value={this.state.username} maxLength="11" onChange={this.changeName} /><br/>
                <input type="password" value={this.state.password} onChange={this.changepwd} /><br/><br/>
                <button onClick={this.login}>登录</button>
            </div>
        );
    }
    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);

相关文章

  • redux

    单独使用redux redux是核心库 与react配合使用redux 安装react-redux react-r...

  • react-redux

    使用react-redux,可以更方便的使用redux开发 先install react-redux使用react...

  • 一个完整小巧的Redux全家桶项目

    OneArticle: 使用React-Native开发,使用Redux,React-Redux,Redux-Pe...

  • redux note(一)

    redux 搭配 React使用 Redux和React之间没有关系,Redux支持React, Angular,...

  • react-redux框架之connect()与Provider

    react-redux 在react-redux 框架中,给我提供了两个常用的API来配合Redux框架的使用,其...

  • React-redux的使用

    React-redux是一个第三方模块,它可以帮我们在react中更方便的使用redux,使用React-redu...

  • 深入解析React-redux插件入门

    react-redux是使用redux开发react时使用的一个插件,另外插一句,redux不是react的产品,...

  • React-redux插件入门实战

    react-redux是使用redux开发react时使用的一个插件,另外插一句,redux不是react的产品,...

  • react-redux

    redux 全局状态管理 react-redux 优化模块 优化redux的使用过程 通过react-redux ...

  • React-Redux 使用

    目前使用版本 建议先了解 Redux 的使用!Redux使用(纯Redux使用) React-Redux 是 Re...

网友评论

      本文标题:react中使用redux

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