1. 首先安裝相關(guān)依賴
yarn add react-router-dom redux react-redux axios redux-logger redux-thunk -S or npm i xxxx -S
2. 創(chuàng)建Store文件夾及內(nèi)部文件(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';
// 相關(guān)中間件
import thunk from 'redux-thunk';
import logger from 'redux-logger'
// redux 調(diào)試工具
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 請(qǐng)求封裝
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';
// 首頁(yè)接口數(shù)據(jù)
export const getHomeData = () => get(rootUrl + '/api/home/content')
3. 連接redux到項(xiàng)目中桐款,在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. 創(chuàng)建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調(diào)用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'
// 調(diào)用 actionCreator 方法,調(diào)取接口數(shù)據(jù)
import { getHomeDataAction } from './Store/actionCreator'
// 動(dòng)態(tài)路由設(shè)置
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 編寫登錄函數(shù)
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 中進(jìn)行判斷
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中調(diào)用接口
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);