在 ReactJS 中提交表单后未获取任何数据

Not getting any data after form submission in ReactJS

提交我的表单后,我没有在控制台上收到提交的数据,而且页面没有路由

我不明白这背后的原因。搜索了 2 天,但仍然没有得到合适的答案。谁能告诉我解决方法?

import axios from "axios";
import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
// import { createBrowserHistory as history } from "history";
import { withRouter } from "react-router-dom";
import DoneStatus from "./DoneStatus";

class Body extends React.Component {
  titleDescMap = new Map();
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChangeTitle = this.handleChangeTitle.bind(this);
    this.handleChangeDescription = this.handleChangeDescription.bind(this);
    this.handleCheckBoxChange = this.handleCheckBoxChange.bind(this);
  }

  state = {
    countTodo: 1,
    valueTitle: "",
    valueDescription: "",
    checkStatus: false,
    routing: false,
  };

  statesStatus() {
    return {
      checkStatus: this.state.checkStatus,
    };
  }

  handleChangeTitle(event) {
    this.setState({
      valueTitle: event.target.value,
    });
  }

  handleChangeDescription(event) {
    this.setState({
      valueDescription: event.target.value,
    });
  }

  handleCheckBoxChange(event) {
    this.setState((prev) => ({ checkStatus: !prev.checkStatus }));
    console.log(this.state.checkStatus);
  }

  handleSubmit(event) {
    // Debugging my states
    console.log("Id: " + this.state.id);
    console.log("Title: " + this.state.valueTitle);
    console.log("Description: " + this.state.valueDescription);
    console.log("Check Status: " + this.state.checkStatus);
    event.preventDefault();

    var previousTitle = this.titleDescMap.has(this.state.valueTitle);

    // Sending data to database

    // Checking if any title and desc is previously stored
    if (previousTitle) {
      alert("Please Enter Another Title (which you have never used)");
    } else {
      // Setting the values in title and description into Map
      this.titleDescMap.set(this.state.valueTitle, this.state.valueDescription);
      console.log(this.titleDescMap);

      // Updating id as counter increases 1
      this.setState((previousState) => ({
        countTodo: previousState.countTodo + 1,
      }));

      if (this.state.checkStatus) {
        const backendData = {
          countTodo: this.state.countTodo,
          title: this.state.valueTitle,
          description: this.state.valueDescription,
        };

        axios
          .post("https://todo-list-site.herokuapp.com/todo-data", backendData)
          .then((data) => {
            console.log(data);
            this.props.history.push("/submit");
          })
          .catch((err) => {
            console.error("Error");
          });

        console.log(backendData);
      }
    }
  }

  render() {
    console.log(this.state.checkStatus);
    return (
      <div className="body-container">
        <p className="body-direction">Fill To Save Your Todo</p>
        <form method="post" onSubmit={this.handleSubmit}>
          <div className="form-group">
            <label>Title</label>
            <input
              type="text"
              className="form-control"
              placeholder="Title here"
              value={this.state.valueTitle}
              onChange={this.handleChangeTitle}
            />
          </div>
          <div className="form-group">
            <label>Description</label>
            <br />
            <textarea
              className="form-control"
              placeholder="Description here"
              rows="4"
              cols="40"
              value={this.state.valueDescription}
              onChange={this.handleChangeDescription}
            />
          </div>
          <div className="form-check">
            <input
              type="checkbox"
              className="form-check-input"
              onChange={this.handleCheckBoxChange}
            />
            <label className="form-check-label body-input-label">
              Save Permanently
            </label>
          </div>
          <button
            type="submit"
            // onClick={() => history().push("/submit")}
            className="btn btn-primary"
          >
            + Add
          </button>
        </form>
      </div>
    );
  }
}

export default withRouter(Body);

我已经根据这个问题的给定解决方案更新了我的代码。但仍然没有得到正确的输出

我想将表单中的所有数据发送到我的后端并在另一个页面上呈现。 数据正在提交,但我没有在控制台上获取它。路由也是这里的主要问题。

我添加了包含所有路线的文件

import Header from "./Header";
import Body from "./Body";
import DoneStatus from "./DoneStatus";
import Saved from "./Saved";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
// import Footer from "./Footer";

class App extends React.Component {
  render() {
    const body = new Body();
    const checkStatus = body.statesStatus();
    return (
      <React.Fragment>
        <Router>
          <Header />
          <Switch>
            <Route
              exact
              path="/"
              render={() => {
                return (
                  <div className="app-container">
                    <Body />
                  </div>
                );
              }}
            ></Route>
          </Switch>
          <Switch>
            <Route
              exact
              path="/saved"
              render={() => {
                return <Saved />;
              }}
            ></Route>
          </Switch>
          {/* <Footer /> */}
          <Switch>
            <Route
              exact
              path="/submit"
              render={() => {
                return <DoneStatus checkedStatus={checkStatus.checkStatus} />;
              }}
            ></Route>
          </Switch>
        </Router>
      </React.Fragment>
    );
  }
}

export default App;

我认为您缺少处理承诺,请找到以下解决方案:

axios.get(`https://todo-list-site.herokuapp.com/todo-data`)
  .then(backendData => {
    console.log(backendData);
  })

你没有在等待你的 POST 完成,正如@Drew Reese 指出的那样,你在调用 history 错误的

handleSubmit(event) {
  // Debugging my states
  console.log("Id: " + this.state.id);
  console.log("Title: " + this.state.valueTitle);
  console.log("Description: " + this.state.valueDescription);
  console.log("Check Status: " + this.state.checkStatus);
  event.preventDefault();

  var previousTitle = this.titleDescMap.has(this.state.valueTitle);

  // Sending data to database

  // Checking if any title and desc is previously stored
  if (previousTitle) {
    alert("Please Enter Another Title (which you have never used)");
  } else {
    // Setting the values in title and description into Map
    this.titleDescMap.set(this.state.valueTitle, this.state.valueDescription);
    console.log(this.titleDescMap);

    // Updating id as counter increases 1
    this.setState((previousState) => ({
      countTodo: previousState.countTodo + 1,
    }));

    if (this.state.checkStatus) {
      const backendData = {
        countTodo: this.state.countTodo,
        title: this.state.valueTitle,
        description: this.state.valueDescription,
      };

      axios.post(
        "https://todo-list-site.herokuapp.com/todo-data",
        backendData
      ).then((response) => {
        console.log(response);
        history.push("/submit");
      }).catch((error) => {
        console.error(error);
      });

    }
  }
}

另外,你不是在等待 countTodo 状态被设置后将其发送到后端,这有时可能会给你带来意想不到的行为