请帮助我解决此问题。props. history. push('/')在CLASS组件中不起作用。因为我们不再具有任何使用历史记录的范围。无法实现导航。请提供帮助。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;
我从所有的推荐信中挑选了。
1条答案
按热度按时间ftf50wuq1#
您需要使用React Router库提供的withRouter高阶组件才能访问这些 prop (自动访问
history
和location
)。导入它,然后将导出更改为
[Note这假设您使用的是React Router v5或更早版本-v6中没有
withRouter
,v6是最新版本。但您使用类组件意味着您使用的是较早版本- v6仅在使用函数组件时才能正常工作,因为withRouter
已被Hooks取代。]