我在尝试理解最佳实践和处理重定向的位置时遇到了很大的困难。
我找到了一个创建 ProtectedRoute
组件的示例,其设置如下:
const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<Route {...rest} render={props => (rest.authenticatedUser ? (<Component {...props}/>) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
};
并像这样使用
<ProtectedRoute path="/" component={HomePage} exact />
我使用redux-thunk
确保我的actions可以使用异步fetch
请求,并且设置类似于以下内容:
Actions
export const loginSuccess = (user = {}) => ({
type: 'LOGIN_SUCCESS',
user
});
...
export const login = ({ userPhone = '', userPass = '' } = {}) => {
return (dispatch) => {
dispatch(loggingIn());
const request = new Request('***', {
method: 'post',
body: queryParams({ user_phone: userPhone, user_pass: userPass }),
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
})
});
fetch(request)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(loggingIn(false));
return response;
})
.then((response) => response.json())
.then((data) => dispatch(loginSuccess(data.user[0])))
.catch((data) => dispatch(loginError(data)));
};
};
Reducers
export default (state = authenticationReducerDefaultState, action) => {
switch (action.type) {
...
case 'LOGIN_SUCCESS':
return {
...state,
authenticatedUser: action.user
};
default:
return state;
}
};
在哪里以及如何处理重定向到登录页面之前的位置,并且如何确保这仅在登录成功的情况下发生?
redirectToReferrer
并成功在LOGGIN_SUCCESS
动作处理程序中更改它。但除此之外,一切都很好! - Jordan