[英]How to redirect a user after a successful login with React
I have a LoginForm component like this:我有一个这样的 LoginForm 组件:
// ...
import { connect } from 'react-redux';
import { userLogin } from '../../store/actions/authActions';
class LoginForm extends Component {
state = {
email: '',
password: ''
};
handleInputChange = event => {
// ...
}
handleFormSubmit = event => {
this.preventDefault();
this.props.userLogin(this.state);
}
render() {
return (
// ....
);
}
}
const mapDispatchToProps = dispatch => {
return {
userLogin: loginData => dispatch(userLogin(loginData))
}
}
export default connect(null, mapDispatchToProps)(LoginForm);
and for authActions.js
I have the following content:对于authActions.js
我有以下内容:
import API from '../../utils/API';
import { USER_LOGIN, USER_LOGOUT } from './authTypes';
const _userLogin = payload => {
return {
type: USER_LOGIN,
payload,
};
};
const _userLogout = payload => {
return {
type: USER_LOGOUT,
payload,
};
};
export const userLogin = payload => {
return dispatch => {
API.post('/auth', payload)
.then(response => {
const { auth_token, current_user } = response.data;
localStorage.setItem('auth_token', auth_token);
dispatch(_userLogin(current_user.data));
})
.catch(error => {
localStorage.removeItem('auth_token');
dispatch(_userLogout(error.response));
});
};
};
My problem is, how to redirect the user after a successful login.我的问题是,如何在成功登录后重定向用户。 I already tried something like:我已经尝试过类似的东西:
history.js
file with the following:使用以下内容创建一个history.js
文件:import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
and change the userLogin
action like this:并像这样更改userLogin
操作:
export const userLogin = payload => {
return dispatch => {
API.post('/auth', payload)
.then(response => {
const { auth_token, current_user } = response.data;
localStorage.setItem('auth_token', auth_token);
dispatch(_userLogin(current_user.data));
history.push('/');
})
.catch(error => {
localStorage.removeItem('auth_token');
dispatch(_userLogout(error.response));
});
};
};
But this prevents the Login to work.但这会阻止登录工作。 for some reason, with this change, the localStorage and the state are not updated.出于某种原因,通过此更改,localStorage 和 state 不会更新。
I changed my userLogin
action to use async/await like this:我将我的userLogin
操作更改为使用 async/await,如下所示:
export const userLogin = payload => {
return async dispatch => {
try {
const response = await API.post('/auth', payload);
const { auth_token, current_user } = response.data;
localStorage.setItem('auth_token', auth_token);
dispatch(_userLogin(current_user.data));
console.log(response);
history.push('/');
} catch (error) {
localStorage.removeItem('auth_token');
dispatch(_userLogout(error));
}
};
};
With this change, the token on localStorage and the state are updated.通过此更改,localStorage 和 state 上的令牌将更新。 And looking at the address bar (browser), I can see that the redirect works (URL is updated).查看地址栏(浏览器),我可以看到重定向有效(URL 已更新)。 But the page is not refreshed, I still see the LoginForm
component instead of the component of the page I redirected to.但是页面没有刷新,我还是看到了LoginForm
组件,而不是我重定向到的页面的组件。
My routes definition looks like:我的路线定义如下:
function AppRouter() {
return (
<Router>
<Switch>
<ProtectedRoute exact path="/" component={Dashboard} />
<Route exact path="/login" component={LoginForm} />
<Route exact path="/signup" component={SignupForm} />
<Route component={NotFound} />
</Switch>
</Router>
);
}
Why are you using redux and complicating your process?为什么您使用 redux 并使您的过程复杂化? You should import the authActions.js as a class and perform the request (not as a prop callback).您应该将 authActions.js 作为 class 导入并执行请求(而不是作为道具回调)。 As the promise resolves from the fetch, you can redirect from there.由于 promise 从提取中解析,您可以从那里重定向。 The auth token or session id should be saved as a http cookie instead of saving it to localStorage.身份验证令牌或 session id 应保存为 http cookie,而不是将其保存到 localStorage。
Solution found:找到的解决方案:
After changing my userLogin
action creator to use async/await like this:将我的userLogin
操作创建者更改为使用 async/await 后,如下所示:
export const userLogin = payload => {
return async dispatch => {
try {
const response = await API.post('/auth', payload);
const { auth_token, current_user } = response.data;
localStorage.setItem('auth_token', auth_token);
dispatch(_userLogin(current_user.data));
console.log(response);
history.push('/');
} catch (error) {
localStorage.removeItem('auth_token');
dispatch(_userLogout(error));
}
};
};
I had also to change the routes definition.我还必须更改路线定义。 First changed the imports:首先更改了导入:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
to至
import { Router, Route, Switch } from 'react-router-dom';
and then pas thw history to the router:然后将历史记录传递给路由器:
<Router history={history}>
<Switch>
<ProtectedRoute exact path="/" component={Dashboard} />
<Route exact path="/login" component={LoginForm} />
<Route exact path="/signup" component={SignupForm} />
<Route component={NotFound} />
</Switch>
</Router>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.