[英]How can I conditionally redirect to a page after the axios response in react?
如果 axios api 为空或状态最初为空,我如何有条件地重定向到页面。 在下面的代码中,我使用 axios 更新状态,并且用户信息在状态中可用,但代码继续调用http://userapi.com/login
循环。 我想要实现的是,如果 userinfo 状态最初为空,则重定向到登录页面并进行身份验证。
class MyComponent extends React.Component {
constructor() {
super()
this.state = {
userinfo:{}
}
}
componentDidMount(){
axios.get('http://userapi.com/user')
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
})
.catch(err => {
console.log("Fetch error", err)
})
if (Object.keys(this.state.userinfo).length === 0) {
window.location = 'http://userapi.com/login';
}
}
render() {
return (
<React.Fragment>
<Header>Welcome</Header>
</React.Fragment>
)
}
}
我能够很好地重定向,但问题在于连续循环。 即使用户信息正在存储重定向被调用(发生在循环中)
Axios 返回Promise,因此下面的if
条件代码在更新then
块中状态的函数之前执行。 因此,如果您需要在请求成功后检查更新的状态值,请将您的条件放入then
块中。
componentDidMount() {
axios
.get('http://userapi.com/user')
.then((res) => {
const userinfo = res.data;
this.setState({ userinfo }, () => {
if (Object.keys(this.state.userinfo).length === 0) {
window.location = 'http://userapi.com/login';
}
});
})
.catch((err) => {
console.log('Fetch error', err);
});
}
您可以尝试以下方法:
class HeaderComponent extends React.Component {
constructor() {
super()
this.state = {
userinfo:{}
}
}
componentDidMount(){
axios.get('http://userapi.com/user')
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
})
.catch(err => {
console.log("Fetch error", err)
})
}
componentDidUpdate(prevProps, { userinfo }) {
if (userinfo !== this.state.userinfo
&& Object.keys(this.state.userinfo.w3idUser || {}).length === 0) {
window.location = 'http://userapi.com/login';
}
}
render() {
return (
<React.Fragment>
<Header>Welcome</Header>
</React.Fragment>
)
}
}
问题是this.state.w3idUser
永远不存在,因为您将响应映射到userInfo
状态。
我猜问题是componentDidMount
,你在 axios 完成它的get
请求之前重定向,像下面这样重构你的代码,你可以显示微调器的种类,直到 axios 返回值:
componentDidMount(){
axios.get('http://userapi.com/user')
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
if (Object.keys(this.state.w3idUser).length === 0) {
window.location = 'http://userapi.com/login';
}
})
.catch(err => {
console.log("Fetch error", err)
})
}
这取决于您使用的路由器,但如果您想要 javascript 方式,请检查以下代码:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");
在这里,当您收到回复时...
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
})
检查 res.data 以获取用户信息。 如果您确实收到了用户,那么您可以设置状态,如果没有用户重定向到登录页面。
至于重定向查看react-router
或react-router-dom
我不会使用纯 javascript 在 React 应用程序中重定向/导航。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.