简体   繁体   English

在 React 中的保护子句失败后,如何立即重定向到不同的页面?

[英]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.

相关问题 如何在反应中的 axios 响应之后有条件地重定向到页面? - How can I conditionally redirect to a page after the axios response in react? 如何在没有保护条款的情况下重写 jQuery? - How can I rewrite jQuery without guard clause? React - 在 Button 的 OnClick 满足某些条件后如何重定向到另一个页面? - React - How can I redirect to another page after some conditions are met on the OnClick of a Button? 单击按钮后如何重定向到其他页面? - How do I redirect to a different page after clicking a button? 如何将 /:user 链接重定向到 react redux 中的 404 页面 - How can I redirect a /:user link to 404 page in react redux 如何在 React js 中将登录重定向到当前页面? - How can I redirect login to current page in react js? 如何在反应原生功能成功后立即启动新功能 - How can I initiate a new function, immediately after a function is successful in react native OAuth 2 流程完成后如何重定向父页面? - How can I redirect the parent page after OAuth 2 flow is complete? 我的Facebook页面被点赞后,如何添加重定向? - How can I add a redirect for after my Facebook page is liked? 在此代码中注册后如何重定向到登录页面 - How can I redirect to login page after registration in this code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM