登录成功后重定向到之前的路由 [英] Redirect to previous route after a login success
问题描述
我花了很长时间试图了解执行此操作的最佳方法以及在何处处理此重定向.
我找到了一个创建 ProtectedRoute
组件的例子,它是这样设置的
const ProtectedRoute = ({ component: Component, ...rest }) =>{返回 (<Route {...rest} render={props =>(rest.authenticatedUser ? (<Component {...props}/>) : (<重定向到={{路径名:'/登录',状态:{来自:props.location}}}/>))}/>);};
就这样使用
我使用 redux-thunk
来确保我可以在我的操作中使用异步 fetch
请求,并且这些请求是这样设置的
操作
export const loginSuccess = (user = {}) =>({类型:'登录_成功',用户});...export const login = ({ userPhone = '', userPass = '' } = {}) =>{返回(调度)=>{调度(登录());const request = new Request('***', {方法:'发布',正文:queryParams({ user_phone: userPhone, user_pass: userPass }),标题:新标题({'内容类型':'应用程序/x-www-form-urlencoded;字符集=UTF-8'})});获取(请求).then((响应) => {如果(!响应.确定){抛出错误(response.statusText);}调度(登录(假));返回响应;}).then((响应) => response.json()).then((data) => dispatch(loginSuccess(data.user[0]))).catch((data) => dispatch(loginError(data)));};};
减速器
export default (state = authenticationReducerDefaultState, action) =>{开关(动作.类型){...案例登录_成功":返回 {...状态,认证用户:action.user};默认:返回状态;}};
在我被重定向到登录页面之前,我将在哪里以及如何处理重定向到我要去的任何地方,以及如何确保这仅在登录获取承诺成功时发生?
您的受保护路由很好.当用户未通过身份验证时,这会将您路由到登录路由.
在你的高级 react-router
你需要嵌套:
创建登录路由.
然后在您的 Login
路由组件中,您将渲染 UI 以让用户登录.
class Login 扩展 React.Component {构造函数(道具){超级(道具);this.state = {用户电话:'',用户密码:''}}句柄登录(){this.props.login({ userPhone, userPass })}handlePhoneChange(事件){const { value } = event.currentTarget;this.setState({ userPhone: value });}handlePasswordChange(事件){const { value } = event.currentTarget;this.setState({ userPass: value });}使成为() {//这是我们获取旧路由的地方 - 从重定向的状态const { from } = this.props.location.state ||{来自:{路径名:'/'}}const { auth } = this.props如果(auth.redirectToReferrer){返回 (<重定向到={from}/>)}返回 (<div><输入值={this.state.userPhone}onChange={this.handlePhoneChange.bind(this)}/><输入类型=密码"值={this.state.userPass}onChange={this.handlePasswordChange.bind(this)}/><button onClick={this.handleLogin.bind(this)}>登录</button>
)}}
该组件将调用 login action-creator 函数(该函数将依次调用您的 API).
如果成功,这将改变 redux 状态.这将重新渲染 Login 组件,如果 auth.redirectToReferrer
为真,将执行重定向.(见上面的代码片段)
参见 https://reacttraining.com/react-router/web/文档的示例/身份验证工作流程.
I am having a hell of a time trying to understand the best way to do this and where to even handle this redirect at.
I found an example of creating a ProtectedRoute
component which is setup like this
const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<Route {...rest} render={props => (rest.authenticatedUser ? (<Component {...props}/>) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
};
And used like this
<ProtectedRoute path="/" component={HomePage} exact />
I use redux-thunk
to make sure I can use async fetch
requests in my actions and those are setup something like this
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;
}
};
Where and how would I go about handling a redirect to wherever I was going before I was redirected to the login page, and how can I make sure this only happens on a success from the login fetch promise?
Your protected route is good. This will route you to the login route when a user is not authenticated.
In your high level react-router <router>
you will need to nest:
<Route path="/login" component={Login}/>
to create a Login route.
Then in your Login
route component you will render the UI to let users login.
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
userPhone: '',
userPass: ''
}
}
handleLogin() {
this.props.login({ userPhone, userPass })
}
handlePhoneChange(event) {
const { value } = event.currentTarget;
this.setState({ userPhone: value });
}
handlePasswordChange(event) {
const { value } = event.currentTarget;
this.setState({ userPass: value });
}
render() {
// this is where we get the old route - from the state of the redirect
const { from } = this.props.location.state || { from: { pathname: '/' } }
const { auth } = this.props
if (auth.redirectToReferrer) {
return (
<Redirect to={from}/>
)
}
return (
<div>
<input
value={this.state.userPhone}
onChange={this.handlePhoneChange.bind(this)}
/>
<input
type="password"
value={this.state.userPass}
onChange={this.handlePasswordChange.bind(this)}
/>
<button onClick={this.handleLogin.bind(this)}>Log in</button>
</div>
)
}
}
This component will call the login action-creator function, (which will in turn call your API).
This will change the redux state if it is successful. This will re-render the Login component, and will do a redirect if auth.redirectToReferrer
is true. (see code snippet above)
See https://reacttraining.com/react-router/web/example/auth-workflow for the docs.
这篇关于登录成功后重定向到之前的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!