明白我的意思
我正在做一个项目,我从开始
react-redux-starter-kit
它是使用react react路由器react路由器redux redux。。。
并且一些页面需要用户登录,
所以在route.js中
1.我检查用户是否未登录,导航到登录页面,
如果用户登录成功,则将用户信息保存到存储
2.如果用户登录但刷新页面,商店会丢失用户信息,所以我会发送一个操作来重新加载用户信息
全部工作
但当用户进入某个页面(如仪表板)时
如果再执行一次操作,商店中的用户信息将丢失
我不知道为什么
路由器
export default function (store) {
const requireAuth = (nextState, replace, cb) => {
function checkAuth () {
const user = store.getState().user
if (!user.user_id) {
replace(__DEV__ ? SiteUrl + 'login' : '/login')
}
cb()
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth)
} else {
checkAuth()
}
}
return (
<Route path='/'} >
<IndexRoute component={HomeView} />
<Route path='setitems' component={SetItemsView} onEnter={requireAuth}/>
<Route path='404' component={NotFoundView} />
<Redirect from='*' to='404' />
</Route>
)
}
auth.js
function requestLogin () {
return {
type: LOGIN_REQUEST
}
}
function loginSuccess (user) {
return {
type: LOGIN_SUCCESS,
user
}
}
function loginError () {
return {
type: LOGIN_FAILURE
}
}
export function isLoaded (globalState) {
return globalState.user && globalState.user.user_id
}
export function getUserLoad () {
return function (dispatch) {
dispatch(requestLogin())
return getUserAction()
.then(function (response) {
var data = response.data
if (data.msg) {
dispatch(loginError())
return {}
}
return data.res
})
.then(function (user) {
dispatch(loginSuccess(user))
})
}
}
function getUserAction () {
return axios.get(GetUser)
}
userReducer.js
function user (state = {}, action) {
switch (action.type) {
case 'LOGIN_SUCCESS' :
return action.user
case 'LOGIN_REQUEST':
console.log('LOGIN_REQUEST')
return state
case 'LOGIN_FAILURE':
console.log('LOGIN_FAILURE')
return state
default:
return {}
}
}
export default user
dashboard page load items list
function requestItems (setitems) {
return {
type: ITEMS_REQUEST,
items: setitems.items
}
}
function itemsSuccess (items) {
return {
type: ITEMS_SUCCESS,
items
}
}
function itemsFailure () {
return {
type: ITEMS_FAILURE
}
}
export function loadItemsAction (page) {
return function (dispatch, getState) {
dispatch(requestItems(getState().setitems))
return axios.get(GetItemsUrl, page)
.then(function (response) {
var data = response.data
return data
})
.then(function (data) {
if (data.msg) {
dispatch(itemsFailure())
} else {
dispatch(itemsSuccess(data.res.items))
}
})
}
}