我花了很长时间试图了解执行此操作的最佳方法以及在哪里处理此重定向。
我找到了一个创建 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
来确保我可以在我的操作中使用异步fetch
请求,并且这些请求的设置如下
操作
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)));
};
};
reducer
export default (state = authenticationReducerDefaultState, action) => {
switch (action.type) {
...
case 'LOGIN_SUCCESS':
return {
...state,
authenticatedUser: action.user
};
default:
return state;
}
};
在我被重定向到登录页面之前,我将在哪里以及如何处理重定向到我要去的任何地方,以及如何确保这仅在登录获取 promise 成功时发生?
最佳答案
您的 protected 路线很好。当用户未经身份验证时,这会将您路由到登录路由。
在你的高级 react 路由器中 <router>
你需要嵌套:
<Route path="/login" component={Login}/>
创建登录路由。
然后在你的Login
中您将渲染 UI 以让用户登录的路由组件。
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>
)
}
}
该组件将调用登录操作创建器函数(该函数将依次调用您的 API)。
如果成功,这将改变 redux 状态。这将重新渲染登录组件,并在 auth.redirectToReferrer
条件下执行重定向。是真的。 (参见上面的代码片段)
参见https://reacttraining.com/react-router/web/example/auth-workflow用于文档。
关于reactjs - 登录成功后重定向到上一个路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535919/