我正在使用HOC进行经过身份验证的路由。我想在重定向到登录页面之前检查本地存储中是否有登录用户,但是在应用加载时,它首先会重定向,然后再登录本地存储。
class App extends Component {
render() {
return (
<div className="App">
<BrowserRouter>
<Route render={({ history }) => (
<div className="App">
<Navbar currUser={this.props.currUser} logout={this.props.logout} history={history}/>
<Switch>
<Auth
exact path="/"
component={HomePage}
currUser={this.props.currUser}
loadRecipes={this.props.loadRecipes}
recipes={this.props.recipes}
/>
<Route
path="/login"
render={(props) => (<LoginPage {...props} login={this.props.login} />)}
/>
</Switch>
</div>
)} />
</BrowserRouter>
</div>
);
}
}
const Auth = ({ component: Component, ...rest }) => {
const currUser = rest.currUser;
return (
<Route {...rest} render=
{props =>
currUser ?
(<Component {...props} {...rest} />) :
(<Redirect to={{ pathname: "/login", state: currUser }} />)
} />
)
}
const mapStateToProps = (state) => {
return {
currUser: state.login.currUser,
recipes: state.recipe.recipes,
recipe: state.recipe.recipe,
user: state.user.userToDisplay,
}
}
const mapDispatchToProps = {
...loginActions,
...recipeActions,
...userActions
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
export const login = (credentials) => {
return async (dispatch) => {
try {
const user = await UserService.login(credentials);
dispatch({ type: 'SET_CURR_USER', user })
return true;
} catch (err) {
return false
}
}
}
async function login(credentials) {
try {
const { data } = await axios.post(`${BASE_URL}/login`, credentials);
StorageService.saveToLocal(USER_KEY, data);
return data;
} catch (err) {
throw err;
}
}
我该怎么做才能使该应用程序首先检查是否存在登录用户,如果没有,则重定向?
谢谢!
const loginReducer = (state = {
currUser: ''
}, action) => {
switch (action.type) {
case 'SET_CURR_USER':
return {
...state,
currUser: action.user
}
default:
return state;
}
}
export default loginReducer;
export default {
getFromLocal,
saveToLocal,
removeFromLocal
}
function getFromLocal(key) {
const res = localStorage.getItem(key)
return res ? JSON.parse(localStorage.getItem(key)) : null
}
function saveToLocal(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function removeFromLocal(key) {
localStorage.removeItem(key);
}