【问题标题】:how to submit form data as "create" api method in ReactJS?如何在 ReactJS 中将表单数据作为“创建”api 方法提交?
【发布时间】:2020-08-09 04:47:53
【问题描述】:

在我的“类别”表中有一些列,例如标题、slug、描述。我想在这些列中添加项目。
我的 api 端点看起来像这样:http://localhost:8000/api/p_category/add

如何在 ReactJS 中添加那些动态表单数据?


我可能是 reactjs 的新手。如果有人可以帮助我,那就太好了,我想要解决的是。非常感谢您。

原始数据:

{
    "title": "",
    "slug": "",
    "description": ""
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这个例子可以帮助你。

    import React, { Component } from 'react';
    import Axios from 'axios';
    
    export default class example extends Component {
        constructor(props) {
            super(props);
    
            this.state = {
                users: [],
            };
        }
    
        componentDidMount() {
            Axios.get('http://127.0.0.1:8000/users/')
                .then(function (response) {
                    this.setState({
                        users: response.data,
                    });
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    
        render() {
            const { users } = this.state;
            return users.lenght > 0 ? (
                <table striped>
                    <thead>
                        <tr>
                            <td>ID</td>
                            <td>Username</td>
                            <td>Email</td>
                        </tr>
                    </thead>
                    <tbody>
                        {users.map((user) => {
                            return (
                                <tr key={user.id}>
                                    <td>{user.id}</td>
                                    <td>{user.username}</td>
                                    <td>{user.email}</td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            ) : (
                <h1>No data available!</h1>
            );
        }
    }
    

    【讨论】:

      【解决方案2】:

      要从服务器加载数据,您应该使用ajax 请求。 Js 具有fetch 功能,允许您向服务器发出ajax 请求。例如,您可以在没有数据的情况下呈现您的表格并在componentDidMount 生命周期中发出ajax 请求。这允许您在上传数据后重新呈现您的表格。

      state = {
          tableData: undefined,
      }
      
      componentDidMount = () => {
          fetch(url, [options]).then(
              data => this.setState(() => ({tableData: data.data.tableData}))
          )
      }
      
      render() {
          const {tableData} = this.state;
          retrun (
              <Table><TableHeader>{tableData.map(row => <TableRow rowData={row} />)}</Table>
          )
      }
      

      我只是写了一个例子,以便你更好地理解这个想法

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 2019-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多