Ich möchte bei einigen Benutzeraktionen eine Navigation durchführen, z. B. beim Senden einer Schaltfläche. Angenommen, der Benutzer klickt auf die Schaltfläche „Kontakt hinzufügen“, möchte ich, dass der React-Router auf der Startseite „/“ umleitet. Derzeit stehe ich vor diesem Problem --> TypeError: Cannot readproperties of undefined (reading 'push') würde mich über die Hilfe von Experten sehr freuen.
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 ({(value) => { const { dispatch } = value; return ( ); } } export default AddContacts;); }}Add Contacts
Dies ist die App.js-Datei
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 (); } export default App; {" "} {" "} {" "}{" "} } />{" "} } />{" "} } />{" "}
如何在 React Router v6 中重定向
问题
这是因为您尝试从不存在的
navigate
属性进行导航,它是未定义的。useNavigate
挂钩仅与函数组件兼容,因此如果您想要/需要将navigate
与类组件一起使用,则必须转换AddContacts code> 到函数组件,或者滚动您自己的自定义
withRouter
高阶组件来注入“路由道具”,例如来自react-router-dom 的
v5.x 做到了。withRouter
HOC解决方案
我不会介绍如何将类组件转换为函数组件。下面是一个自定义
withRouter
HOC 示例:并使用新的 HOC 装饰
AddContacts
组件。现在会将
navigate
属性(以及您设置的任何其他属性)传递给装饰组件,并且this.navigate
现在将已定义。此外,导航 API 从 v5 更改为 v6,不再使用直接的
history
对象。navigate
是一个函数而不是一个对象。要使用您调用函数并传递 1 或 2 个参数,第一个是目标路径,第二个是带有replace
和/或state
键的可选“选项”对象/值。现在导航如下: