遇到错误消息“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);
使用 navigate 函数进行导航,而不是以前版本的 React Router 中使用的历史对象。语法已更改为:
this.props.navigate("/path");
AddContacts.js 的完整工作代码:
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
此解决方案允许从 React Router v6 中的类组件进行导航,尽管最初的错误表明未定义的导航道具。
以上是在 React Router v6 中尝试重定向时如何解决'TypeError: Cannot Read Properties of Undefined (reading 'push')”?的详细内容。更多信息请关注PHP中文网其他相关文章!