You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件中守卫条件验证失败后如何立即重定向页面?

问题:React类组件中验证失败后如何实现页面重定向

我用ReserveerForm这个React类组件作为网页基础,在componentDidMount()里加了两个校验逻辑:检查GET请求是否携带zaalId参数,再调用接口验证该ID对应的对象是否存在。如果校验失败,我想直接重定向到其他页面,但useNavigate只适用于函数组件,试了this.props.navigation.navigate()却报错this.props.navigation is undefined,该怎么实现?

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;

解决方案

1. 修复withRouter的使用问题

你已经导入了withRouter,但没有用它包裹组件导出,这是this.props.navigation未定义的核心原因。修改导出语句:

export default withRouter(ReserveerForm);

2. 在校验失败时执行重定向

React Router v6中,withRouter会给类组件注入navigate方法,直接用它跳转即可。修改componentDidMount的校验逻辑:

async componentDidMount() {
    const zaalId = this.getZaalId();

    // 先检查zaalId是否存在
    if (!zaalId) {
        console.log("ZaalId required");
        this.props.navigate('/你的目标页面路径'); // 替换成实际跳转地址
        return;
    }

    try {
        const res = await fetch(`https://localhost:7260/Zaal/${zaalId}`);
        const data = await res.json();

        if (!data || data.length === 0) {
            console.log(`No zaal with ID ${zaalId} found`);
            this.props.navigate('/你的目标页面路径'); // 替换成实际跳转地址
            return;
        }
    } catch (error) {
        console.error('验证房间信息时出错:', error);
        this.props.navigate('/你的目标页面路径'); // 接口请求异常时也跳转
    }
}

3. 额外优化建议

  • 删除重复定义的getZaalId方法,保留一个即可
  • 日期输入框的value需要转成ISO字符串格式(截取前16位去掉时区),否则可能显示异常:
    constructor(props) {
        super(props);
        this.state = {
            startDate: new Date().toISOString().slice(0, 16),
            endDate: new Date().toISOString().slice(0, 16),
            roomId: null,
            redirect: false
        };
    }
    

内容的提问来源于stack exchange,提问作者lexalot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:45:30