問題描述
我想對某些用戶操作執行導航,例如按鈕的 onSubmit.假設用戶單擊添加聯系人按鈕,我希望 react-router 在/"中重定向這是主頁.目前我正面臨這個問題-->TypeError:無法讀取未定義的屬性(讀取推送").作為初學者,我非常感謝專家的幫助.
AddContacts.js
import React, { Component } from "react";從../../context"導入{消費者};從../layout/TextInputGroup"導入 TextInputGroup;從uuid"導入 { v4 as uuidv4 };從react-router-dom"導入 { useNavigate };類 AddContacts 擴展組件 {狀態 = {名稱:",電子郵件:",電話:",錯誤:{},};onSubmit = (dispatch, e) =>{e.preventDefault();const { 姓名、電子郵件、電話 } = this.state;//檢查錯誤if (name === "") {this.setState({ errors: { name: "Name is required" } });返回;}如果(電子郵件==="){this.setState({ errors: { email: "Email is required" } });返回;}如果(電話==="){this.setState({ errors: { phone: "Phone is required" } });返回;}常量新聯系人 = {id: uuidv4(),名稱,電子郵件,電話,};dispatch({ type: "ADD_CONTACT", payload: newContact });這個.setState({名稱:",電子郵件:",電話:",錯誤:{},});this.props.navigate.push("/");};onChange = (e) =>this.setState({ [e.target.name]: e.target.value });使成為() {const { 姓名、電子郵件、電話、錯誤 } = this.state;返回 (<消費者>{(值) =>{常量 { 調度 } = 值;返回 (<div className="card mb-3"><div className="card-header">添加聯系人</div><div className=""card-body"><form onSubmit={this.onSubmit.bind(this, dispatch)}><文本輸入組標簽=名稱"名稱=名稱";placeholder=輸入名稱..."值={名稱}onChange={this.onChange}錯誤={errors.name}/><文本輸入組標簽=電子郵件"名稱=電子郵件";類型=電子郵件";placeholder=輸入電子郵件..."價值={電子郵件}onChange={this.onChange}錯誤={errors.email}/><文本輸入組標簽=電話"名稱=電話";placeholder=輸入電話..."價值={電話}onChange={this.onChange}錯誤={errors.phone}/><輸入類型=提交";value="添加聯系人"className="btn btn-light btn-block mt-3"/></表格></div></div>);}}</消費者>);}}導出默認的 AddContacts;
這是 App.js 文件
import React, { Component } from "react";從react-router-dom"導入 { BrowserRouter, Routes, Route, Link };從./components/contacts/Contacts"導入聯系人;從./components/layout/Header"導入標題;從./components/contacts/AddContacts"導入 AddContacts;從./components/pages/About"導入關于;從./context"導入{ Provider };導入bootstrap/dist/css/bootstrap.min.css";導入./App.css";函數應用程序(){返回 (<提供者><瀏覽器路由器><div className="App"><標題品牌=聯系人經理"/><div className=容器"><路線><路由路徑="/";element={<聯系人/>}/>{""}<路由路徑="/contact/add/*"element={<AddContacts/>}/>{""}<路線路徑=約/*"元素={<關于/>}/>{""}</路線>{""}</div>{>"}</div>{>"}</BrowserRouter>{""}</提供者>);}導出默認應用程序;
問題
<塊引用>TypeError:無法讀取未定義的屬性(讀取推送")
這是因為您嘗試從不存在的 navigate
道具導航,它是未定義的.
this.props.navigate.push("/");
useNavigate
鉤子僅與功能組件兼容,因此您希望/需要將 navigate
與類組件一起使用,您必須轉換 AddContacts
到函數組件,或滾動您自己的自定義 withRouter
高階組件以注入路由道具";就像 react-router-dom
v5.x 中的 withRouter
HOC 一樣.
解決方案
我不會介紹將類組件轉換為函數組件.這是一個示例自定義 withRouter
HOC:
const withRouter = WrappedComponent =>道具=>{常量導航 = useNavigate();//等等...其他 react-router-dom v6 鉤子返回 (<包裹組件{...道具}導航={導航}//等等.../>);};
并用新的 HOC 裝飾 AddContacts
組件.
export default withRouter(AddContacts);
現在這會將 navigate
道具(和您設置的任何其他道具)傳遞給裝飾組件,并且 this.navigate
現在將是已定義.
此外,導航 API 從 v5 更改為 v6,不再使用直接的 history
對象.navigate
是一個函數而不是一個對象.要使用您調用函數并傳遞 1 或 2 個參數,第一個是目標路徑,第二個是可選的選項";帶有 replace
和/或 state
鍵/值的對象.
接口 NavigateFunction {(到:到,選項?:{替換?:布爾值;狀態?:狀態 }): 空白;(增量:數字):無效;}
現在如下導航:
this.props.navigate("/");
I want to perform navigation on certain user actions, say onSubmit of a button. suppose a user clicks on the Add contact button I want react-router to redirect in "/" which is the home page. At the moment I am facing this problem--> TypeError: Cannot read properties of undefined (reading 'push'). As a beginner, I would really appreciate experts' help.
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;
Here is the App.js file
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;
Issue
TypeError: Cannot read properties of undefined (reading 'push')
This is cause by you attempting to navigate from a navigate
prop that doesn't exist, it's undefined.
this.props.navigate.push("/");
The useNavigate
hook is only compatible with function components, so of you want/need to use navigate
with a class component you must either convert AddContacts
to a function component, or roll your own custom withRouter
Higher Order Component to inject the "route props" like the withRouter
HOC from react-router-dom
v5.x did.
Solution
I won't cover converting a class component to function component. Here's an example custom withRouter
HOC:
const withRouter = WrappedComponent => props => {
const navigate = useNavigate();
// etc... other react-router-dom v6 hooks
return (
<WrappedComponent
{...props}
navigate={navigate}
// etc...
/>
);
};
And decorate the AddContacts
component with the new HOC.
export default withRouter(AddContacts);
This will now pass a navigate
prop (and any others you set up) to the decorated components and this.navigate
will now be defined.
Additionally, the navigation API changed from v5 to v6, it's no longer the direct history
object being used. navigate
is a function instead of an object. To use you invoke the function and pass 1 or 2 arguments, the first is the target path, the second is an optional "options" object with replace
and/or state
key/values.
interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: State } ): void; (delta: number): void; }
To navigate now as follows:
this.props.navigate("/");
這篇關于以編程方式重定向到反應路由器 v6 中的路由的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!