首页 >web前端 >js教程 >在 React Router v6 中尝试重定向时如何解决'TypeError: Cannot Read Properties of Undefined (reading \'push\')\”?

在 React Router v6 中尝试重定向时如何解决'TypeError: Cannot Read Properties of Undefined (reading \'push\')\”?

Linda Hamilton
Linda Hamilton原创
2024-10-30 14:55:031017浏览

How to Resolve

使用 React Router v6 以编程方式导航:解决 TypeError

问题

遇到错误消息“TypeError: 无法读取未定义的属性(读取 'push') ')" 在用户操作(例如单击提交按钮)后尝试重定向时。这表明用于重定向的导航属性未定义。

解决方案

1。转换为函数组件

使用 useNavigate 钩子在函数组件内进行导航。该钩子仅兼容函数组件。

2.为类组件创建自定义 HOC

自定义 withRouter HOC:

const withRouter = WrappedComponent => props => {
  const navigate = useNavigate();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      navigate={navigate}
      // etc...
    />
  );
};

装饰类组件:

export default withRouter(AddContacts);

3。使用 Navigate 函数

使用 navigate 函数进行导航,而不是以前版本的 React Router 中使用的历史对象。语法已更改为:

this.props.navigate("/path");

AddContacts.js 的完整工作代码:

import React, { Component } from "react";
import { Consumer } from "../../context";
import TextInputGroup from "../layout/TextInputGroup";
import { v4 as uuidv4 } from "uuid";
import withRouter from "./withRouter"; // Custom HOC

class AddContacts extends Component {
  state = {
    name: "",
    email: "",
    phone: "",
    errors: {},
  };

  onSubmit = (dispatch, e) => {
    e.preventDefault();

    const { name, email, phone } = this.state;

    //Check for errors

    if (name === "") {
      this.setState({ errors: { name: "Name is required" } });
      return;
    }
    if (email === "") {
      this.setState({ errors: { email: "Email is required" } });
      return;
    }
    if (phone === "") {
      this.setState({ errors: { phone: "Phone is required" } });
      return;
    }

    const newContact = {
      id: uuidv4(),
      name,
      email,
      phone,
    };
    dispatch({ type: "ADD_CONTACT", payload: newContact });

    this.setState({
      name: "",
      email: "",
      phone: "",
      errors: {},
    });
    this.props.navigate("/"); // Navigate using custom HOC
  };

  onChange = (e) => this.setState({ [e.target.name]: e.target.value });
  render() {
    const { name, email, phone, errors } = this.state;

    return (
      <Consumer>
        {(value) => {
          const { dispatch } = value;

          return (
            <div className="card mb-3">
              <div className="card-header">Add Contacts</div>
              <div className="card-body">
                <form onSubmit={this.onSubmit.bind(this, dispatch)}>
                  <TextInputGroup
                    label="Name"
                    name="name"
                    placeholder="Enter Name..."
                    value={name}
                    onChange={this.onChange}
                    error={errors.name}
                  />
                  <TextInputGroup
                    label="Email"
                    name="email"
                    type="email"
                    placeholder="Enter Email..."
                    value={email}
                    onChange={this.onChange}
                    error={errors.email}
                  />
                  <TextInputGroup
                    label="Phone"
                    name="phone"
                    placeholder="Enter Phone..."
                    value={phone}
                    onChange={this.onChange}
                    error={errors.phone}
                  />
                  <input
                    type="submit"
                    value="Add Contact"
                    className="btn btn-light btn-block mt-3"
                  />
                </form>
              </div>
            </div>
          );
        }}
      </Consumer>
    );
  }
}

export default withRouter(AddContacts); // Export wrapped component

此解决方案允许从 React Router v6 中的类组件进行导航,尽管最初的错误表明未定义的导航道具。

以上是在 React Router v6 中尝试重定向时如何解决'TypeError: Cannot Read Properties of Undefined (reading 'push')”?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn