【问题标题】:Not getting any data after form submission in ReactJS在 ReactJS 中提交表单后没有获取任何数据
【发布时间】:2021-04-22 06:29:11
【问题描述】:

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

我不明白这背后的原因。搜索了 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;

【问题讨论】:

  • 可能的错字:history().push("/submit"); 应该是 history.push("/submit");。你能解释一下你在控制台中期待什么吗?是console.log(backendData);日志吗?
  • @DrewReese 调用history.push() 表明没有可用于历史记录的方法。但是history() 正在显示方法 push()。这就是我使用它的原因。 history.push('/submit') 也没有路由我的页面
  • 哦,你正在创建一个新的历史对象。不要那样做。使用withRouter HOC (大概)提供的this.props.history 对象。您的路由器不知道您正在创建的 thishistory 对象,因此导航将不稳定或根本不起作用。
  • @DrewReese this.props.history 意味着我必须在我的 Body 组件中传递参数 history ,无论我将使用 Body 吗?好的,所以我已经这样做了,它显示Cannot read property 'wrappedComponentRef' of undefined,我更改的代码是this.props.history.push("/submit");export default withRouter(Body); .....import { withRouter } from "react-router-dom";
  • 对不起,我已经签了晚上,但很高兴帮助。干杯。

标签: javascript reactjs routes react-router


【解决方案1】:

您没有等待您的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 状态发送到后端后,您不会等待设置它,这有时可能会导致您出现意外行为

【讨论】:

  • 我无法确定为什么我的控制台上没有任何数据?此外,仍然无法使用history.push("/submit") 路由我的页面
  • 您希望在控制台中看到什么?您应该看到您保存的确切对象console.log(backendData);。而且您可能会在存储之前看到控制台,因为您没有等待 POST 完成来控制台数据。
  • 我在渲染方法等很多地方都使用过console.log()。至少应该打印该数据,因为它不依赖于 post 方法。当我点击复选框时,我想查看我的checkStatus 状态。但在控制台上没有得到任何输出。如果我做错了,请你解释一下。我是 ReactJS 的新手。
  • 这很奇怪,你应该看到控制台。你的控制台有错误吗?看起来您之前有一个错误,并且您的 Body 组件操作没有被执行
  • 路由应该像@Drew Reese 评论的那样。如果您将问题放在管理路线的组件上,我们也许可以帮助您解决那里的问题。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2014-06-19
    • 2022-01-21
    • 1970-01-01
    • 2012-05-07
    • 2020-12-12
    • 2017-07-30
    • 1970-01-01
    相关资源
    最近更新 更多