搜索

首页  >  问答  >  正文

以编程方式重定向到React Router v6中的路由时出现问题

我想对某些用户操作执行导航,例如按钮的 onSubmit。假设用户单击“添加联系人”按钮,我希望反应路由器在主页“/”中重定向。目前我面临这个问题--> TypeError: Cannot readproperties of undefined (reading 'push').作为初学者,我非常感谢专家的帮助。

AddContacts.js

import React, { Component } from "react";
import { Consumer } from "../../context";
import TextInputGroup from "../layout/TextInputGroup";
import { v4 as uuidv4 } from "uuid";
import { useNavigate } from "react-router-dom";

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.push("/");
  };

  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 AddContacts;

这是 App.js 文件

import React, { Component } from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

import Contacts from "./components/contacts/Contacts";
import Header from "./components/layout/Header";
import AddContacts from "./components/contacts/AddContacts";
import About from "./components/pages/About";

import { Provider } from "./context";

import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

function App() {
  return (
    <Provider>
      <BrowserRouter>
        <div className="App">
          <Header branding="Contact manager" />
          <div className="container">
            <Routes>
              <Route path="/" element={<Contacts />} />{" "}
              <Route path="/contact/add/*" element={<AddContacts />} />{" "}
              <Route path="about/*" element={<About />} />{" "}
            </Routes>{" "}
          </div>{" "}
        </div>{" "}
      </BrowserRouter>{" "}
    </Provider>
  );
}

export default App;


P粉693126115P粉693126115379 天前627

全部回复(2)我来回复

  • P粉905144514

    P粉9051445142023-10-31 19:13:17

    如何在 React Router v6 中重定向

    import {  useNavigate  } from "react-router-dom";
    
      const navigate = useNavigate();
      
      const handleClick = () => {
        navigate("/dashboard");
      };

    回复
    0
  • P粉384244473

    P粉3842444732023-10-31 13:19:10

    问题

    这是因为您尝试从不存在的 navigate 属性进行导航,它是未定义的。

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

    useNavigate 挂钩仅与函数组件兼容,因此如果您想要/需要将 navigate 与类组件一起使用,则必须转换 AddContacts 到函数组件,或者滚动您自己的自定义 withRouter 高阶组件来注入“路由道具”,例如来自 react-router-dom 的 withRouter HOC v5.x 做到了。

    解决方案

    我不会介绍如何将类组件转换为函数组件。下面是一个自定义 withRouter HOC 示例:

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

    并使用新的 HOC 装饰 AddContacts 组件。

    export default withRouter(AddContacts);

    现在会将 navigate 属性(以及您设置的任何其他属性)传递给装饰组件,并且 this.navigate 现在将已定义。

    此外,导航 API 从 v5 更改为 v6,不再使用直接的 history 对象。 navigate 是一个函数而不是一个对象。要使用您调用函数并传递 1 或 2 个参数,第一个是目标路径,第二个是带有 replace 和/或 state 键的可选“选项”对象/值。

    现在导航如下:

    this.props.navigate("/");

    回复
    0
  • 取消回复