[英]this.props.history.push('/') IS NOT WORKING in CLASS Component
Please help me to resolve the issue of this.props.history.push('/') IS NOT WORKING in CLASS Component.请帮助我解决 this.props.history.push('/') IS NOT WORKING in CLASS Component 的问题。 As we do not have any scope of using history anymore.因为我们没有任何 scope 的使用历史了。 Unable to implement navigate.无法实施导航。 Please do help.请帮忙。 Same issue with props.location.state.contact.与 props.location.state.contact 相同的问题。
**const { name, email } = props.location.state.contact;**
import React, { Component } from "react";
import "../assets/css/AddContact.css";
import { Navigate } from "react-router-dom";
import { v4 as uuid } from "uuid";
class AddContact extends Component {
state = {
id: uuid(),
name: "",
email: "",
};
add = (e) => {
e.preventDefault();
if (this.state.name === "" || this.state.email === "") {
alert("All fields are required!");
return;
}
this.props.addContactHandler(this.state);
this.setState({ name: "", email: "" });
this.props.history.push("/");
};
render() {
return (
<div className="contactForm">
<h2 className="contactForm__title">Add Contact</h2>
<div className="contactForm__form">
<form action="/" method="post" onSubmit={this.add}>
<div className="contactForm__nameField">
<label htmlFor="name">Name</label>
<br />
<input
type="text"
placeholder="Enter your name"
name="name"
id="name"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div className="contactForm__emailField">
<label htmlFor="email">Email</label>
<br />
<input
type="email"
placeholder="Enter your email"
name="email"
id="email"
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<button className="contactForm__button">Add</button>
</form>
</div>
</div>
);
}
}
export default AddContact;
I tried out from all of my references.我尝试了所有参考资料。
You need to use the withRouter Higher Order Component provided with the React Router library in order to get access to those props ( history
and location
automatically).您需要使用 React Router 库随附的withRouter高阶组件才能访问这些道具(自动history
和location
)。
So just import that, and change your export to所以只需导入它,然后将导出更改为
export default withRouter(AddContact);
[Note that this assumes you are using React Router v5 or before - there is no withRouter
in v6 which is the latest version. [请注意,这假设您使用的是 React Router v5 或之前的版本——最新版本的 v6 中没有withRouter
。 But your use of a class component implies that you are using an earlier version - v6 only works well if you use function components, as withRouter
has been replaced with Hooks.]但是您使用 class 组件意味着您使用的是早期版本 - v6 只有在您使用 function 组件时才能正常工作,因为withRouter
已被 Hooks 取代。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.