[英]How can I immediately redirect to a different page after a failed guard clause in React?
Bellow is a class component I'm using as the basis for a web page. Bellow 是一个 class 组件,我将其用作 web 页面的基础。 As you can see, inside componentDidMount() I have two guard clauses that check if the GET contains a zaalId parameter, and this checks an endpoint to see if the corresponding object with that ID exists.
如您所见,在 componentDidMount() 内部,我有两个保护子句,用于检查 GET 是否包含 zaalId 参数,并检查端点以查看具有该 ID 的相应 object 是否存在。 If it does not exist, I would like it to immediately redirect to a different page.
如果它不存在,我希望它立即重定向到另一个页面。 How can I do this?
我怎样才能做到这一点? useNavigate only works in function components.
useNavigate 仅适用于 function 组件。
import React, { Component } from "react";
import { useNavigate } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
class ReserveerForm extends Component
{
constructor(props) {
super(props);
this.state = {
startDate: new Date(),
endDate: new Date(),
roomId: null,
redirect: false
};
}
async componentDidMount() {
const zaalId = this.getZaalId();
const res = await fetch(`https://localhost:7260/Zaal/${zaalId}`);
const data = await res.json();
if (zaalId == null) {
console.log("ZaalId required");
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
return;
}
}
getZaalId = (event) => {
const queryParameters = new URLSearchParams(window.location.search);
const zaalId = queryParameters.get("zaalId");
return zaalId;
};
async validateZaal(zaalId) {
const res = await fetch(`https://localhost:7260/Zaal/${zaalId}`);
const data = await res.json();
if (zaalId == null) {
console.log("ZaalId required");
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
}
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = event => {
const zaalId = this.getZaalId();
event.preventDefault();
console.log(
`Renting room with id ${zaalId}
from ${this.state.startDate}
to ${this.state.endDate}`
);
};
getZaalId = event => {
const queryParameters = new URLSearchParams(window.location.search)
const zaalId = queryParameters.get("zaalId")
return (zaalId);
}
render() {
return (
< form onSubmit ={ this.handleSubmit}>
< label htmlFor = "startDate" > Start Date:</ label >
< input
type = "datetime-local"
name = "startDate"
value ={ this.state.startDate}
onChange ={ this.handleChange}
/>
< br />
< label htmlFor = "endDate" > End Date:</ label >
< input
type = "datetime-local"
name = "endDate"
value ={ this.state.endDate}
onChange ={ this.handleChange}
/>
< br />
< button type = "submit" > Rent Room </ button >
</ form >
);
}
}
export default ReserveerForm;
I've tried using this.props.navigation.navigate();我试过使用 this.props.navigation.navigate(); but this tells me "this.props.navigation is undefined" in the console.
但这在控制台中告诉我“this.props.navigation is undefined”。
To redirect to a different page after a failed guard clause in a class component, you can use the history object provided by the withRouter HOC.要在 class 组件中的保护子句失败后重定向到其他页面,您可以使用 withRouter HOC 提供的历史记录 object。 First, make sure to wrap your component with withRouter:
首先,确保用 withRouter 包装你的组件:
import { withRouter } from 'react-router-dom';
class ReserveerForm extends Component {...}
export default withRouter(ReserveerForm);
Then, you can use the history.push method to redirect to a different page:然后,您可以使用 history.push 方法重定向到不同的页面:
if (zaalId == null) {
console.log("ZaalId required");
this.props.history.push('/error');
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
this.props.history.push('/error');
return;
}
This will redirect to the /error page if either of the guard clauses fail.如果任一保护子句失败,这将重定向到 /error 页面。 Make sure to import withRouter at the top of your file.
确保在文件顶部导入 withRouter。
You can use the Navigate element in the render()
method:您可以在
render()
方法中使用Navigate 元素:
render() {
if(this.state.redirect) {
return <Navigate to="/error" />
}
// normal code
}
Set the redirect
state variable to true in componentDidMount
to trigger the redirect.在
componentDidMount
中将redirect
state 变量设置为 true 以触发重定向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.