【问题标题】:React posting form data and rendering data from databaseReact 从数据库中发布表单数据和渲染数据
【发布时间】:2019-10-10 15:04:52
【问题描述】:

我是新来的反应。我有一个 POST API,它将用户名和电子邮件 ID 作为输入并返回该特定用户的详细信息。我想通过表单作为请求提交用户名和电子邮件 ID,提交后,我想在 React UI 中以表格形式呈现用户详细信息,即用户名、电子邮件 ID、年龄等。 API 工作正常并返回所需的响应。我该如何解决这个问题?

反应代码:-

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            users: [],
            username: '',
        };

        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleUserNameChange = e => {
        this.setState({ username: e.target.value });
    }


    handleSubmit(e) {
        e.preventDefault();

        const newUser = {
            username: this.state.username,
        };


    }

    componentDidMount() {
         axios.post('http://localhost:8080/api/users', newUser)
            .then(response => {
                console.log('Saved');
                console.log(response.data);
                console.log(this.state.username);
            });
    }




    render() {
        return (
            <div>

                <div>
                  <form onSubmit={this.handleSubmit}>

                      <label>User Name</label>
                      <input type="text" onChange={this.handleUserNameChange} />

                      <button type="submit">Add</button>
                  </form>
                </div>
                <div>
                    <ul>
                        <li>{this.state.username}</li>
                    </ul>
                </div>

            </div>
        );
    }
}

export default App;

【问题讨论】:

  • 你能告诉我们你到目前为止的尝试吗?
  • @vipulp 我已经添加了到目前为止我尝试过的内容。
  • 您也可以在发布请求之后发布响应吗?只是为了确认一下,您想呈现响应的详细信息,对吗?
  • @vipulp 我能够在我的控制台中获得输出。但我无法在我的 UI 中呈现相同的输出。

标签: reactjs forms api


【解决方案1】:

您可以通过以下方式做到这一点。这只是一个基本的实现。根据需要进行修改。

1) 您将在表单中有两个 input 字段用于 usernameemail ID

state={
   username: '',
   emailID: '',

   // also define states for response data user's name, age etc.
 }

还有一个handleEmailChange 函数类似于handleUserNameChange 用于emailID。

2) 在handleSubmit发出post请求:

handleSubmit(e) {
    e.preventDefault();

    const newUser = {
        username: this.state.username,
        emailID: this.state.emailID
    };

    axios.post('http://localhost:8080/api/users', newUser)
        .then(response => {           
            this.setState({}) // get age, name and other data from response and set 
                              //  the states here respectively 
        })
        .catch(error => error);            
}

3) 在表格中渲染

 <table>
  <tr>
    <th>Name</th>
    <th>Email ID</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>{this.state.name}</td>
    <td>{this.state.emailID}</td>
    <td>{this.state.age}</td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2016-11-09
    • 2016-10-22
    相关资源
    最近更新 更多