创建一个登录验证中间件
createLoginMiddleware.js
import {NavigationActions} from "react-navigation"
function createLoginMiddleware() {
return ({dispatch, getState}) => next => action => {
// 判断action type是否为NAVIGATE类型 并且是需要验证的页面
if (action.type == NavigationActions.NAVIGATE && (action.routeName == 'Trade' || action.routeName == 'LiveTelecast')) {
const state = getState()
let appLoginState = state.getIn(['loginState', 'appLoginState']);
// 判断登录状态
if (!appLoginState) {
// 没有登录者跳转到登录页面
dispatch({type: NavigationActions.NAVIGATE, routeName: 'AppLogin'})
return
}
}
return next(action)
}
}
export default createLoginMiddleware
添加中间件
configureStore.prod.js
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { Map } from 'immutable'
import { socket } from './io'
import createSocketIoMiddleware from './socketIo'
import createLoginMiddleware from './loginMiddleware'
import getReducers from '../reducers/index'
// socket中间件
const socketMiddleware = createSocketIoMiddleware(socket)
// 登录验证中间件
const loginMiddleware = createLoginMiddleware()
function configureStore(navReducer, initialState = Map()) {
let enhancer = compose(
applyMiddleware(socketMiddleware, loginMiddleware, thunk)
)
return createStore(getReducers(navReducer), initialState, enhancer)
}
export default configureStore