javascript 此.props.history.push('/')在类组件中不起作用

3qpi33ja  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(95)

请帮助我解决此问题。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;

我从所有的推荐信中挑选了。

ftf50wuq

ftf50wuq1#

您需要使用React Router库提供的withRouter高阶组件才能访问这些 prop (自动访问historylocation)。
导入它,然后将导出更改为

export default withRouter(AddContact);

[Note这假设您使用的是React Router v5或更早版本-v6中没有withRouter,v6是最新版本。但您使用类组件意味着您使用的是较早版本- v6仅在使用函数组件时才能正常工作,因为withRouter已被Hooks取代。]

相关问题