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 ( Add Contacts ); }} ); } } export default AddContacts;
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 中重定向
import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); const handleClick = () => { navigate("/dashboard"); };问题
这是因为您尝试从不存在的
navigate属性进行导航,它是未定义的。this.props.navigate.push("/");useNavigate挂钩仅与函数组件兼容,因此如果您想要/需要将navigate与类组件一起使用,则必须转换AddContacts code> 到函数组件,或者滚动您自己的自定义withRouter高阶组件来注入“路由道具”,例如来自react-router-dom 的v5.x 做到了。withRouterHOC解决方案
我不会介绍如何将类组件转换为函数组件。下面是一个自定义
withRouterHOC 示例:const withRouter = WrappedComponent => props => { const navigate = useNavigate(); // etc... other react-router-dom v6 hooks return ( ); };并使用新的 HOC 装饰
AddContacts组件。现在会将
navigate属性(以及您设置的任何其他属性)传递给装饰组件,并且this.navigate现在将已定义。此外,导航 API 从 v5 更改为 v6,不再使用直接的
history对象。navigate是一个函数而不是一个对象。要使用您调用函数并传递 1 或 2 个参数,第一个是目标路径,第二个是带有replace和/或state键的可选“选项”对象/值。现在导航如下:
this.props.navigate("/");