遇到錯誤訊息「TypeError: 無法讀取未定義的屬性(讀取'push') ')" 在使用者操作(例如點擊提交按鈕)後嘗試重定向時。這表示用於重定向的導航屬性未定義。
使用 useNavigate 鉤子在函數元件內進行導航。此鉤子僅相容於函數組件。
自訂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);
this.props.navigate("/path");
使用 navigate 函數進行導航,而不是先前版本的 React Router 中使用的歷史物件。語法已更改為:
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
AddContacts.js 的完整工作代碼:
此解決方案允許從React Router v6 中的類別組件進行導航,儘管最初的錯誤表明未定義的導航道具。以上是在 React Router v6 中嘗試重新導向時如何解決「TypeError: Cannot Read Properties of Undefined (reading 'push')」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!