我在使用 Axios 时遇到一点问题,我不知道如何在注册或登录后重定向。
这是我的代码:
axios.post("/api/user/signup", { data })
.then(res => {
if (res.status === 200) {
console.log("REDIRECTION avec status => ", res.status);
// how to redirect here
<Redirect to = {{ pathname: "/home" }} />
}
流程到达 console.log
调用,但我无法在 React 中找到如何在它之后重定向。
最佳答案
根据您对 Redirect
组件的使用,我假设您正在使用 React Router 作为路由逻辑库。
React Router (v4) 在渲染时处理路由。
这意味着重定向将在呈现 Redirect
组件时发生。
控制这种情况的一种方法是利用状态。
在 React 中,更改状态会导致重新渲染。
这是一种方法:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isSignedUp: false // <-- initialize the signup state as false
}
}
signup() {
return axios.post("/api/user/signup", { data })
.then(res => {
if (res.status === 200) {
this.setState({ isSignedUp: true }); // after signing up, set the state to true. This will trigger a re-render
}
}
// ...
render() {
if (this.state.isSignedUp) {
// redirect to home if signed up
return <Redirect to = {{ pathname: "/home" }} />;
}
// ... rest of rendering code
}
关于javascript - 使用 Axios 和 React 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900739/