【问题标题】:Create Dynamic Table using Response data in reactJS在 reactJS 中使用响应数据创建动态表
【发布时间】:2018-03-14 11:52:28
【问题描述】:

我的问题是,我想在 reactJS 中打印表格。我已经使用 axios 从 django 视图中获取数据并且得到了响应。但是,我不知道谁将这些数据设置为表格格式。我使用了 react-bootstrap 表。而且我是 ReactJS 的新手。 我的代码片段是:

change(){
axios.get('http://127.0.0.1:8000/users/')
.then(function (response) {
  console.log("in user",response.data[0].id);
  this.setState({
    id: response.data[0].id,
    username: response.data[0].username,
    email: response.data[0].email,
});
})
.catch(function (error) {
  console.log(error);
});

}

但是现在如何在“tbody”标签中使用这个 id、用户名和电子邮件呢?请指导我。谢谢。

【问题讨论】:

    标签: django reactjs axios react-bootstrap


    【解决方案1】:

    在您使用 react-bootstrap 组件的渲染函数中。只需使用

    <tbody>
      <tr>
        <td>{this.state.id}</td>
        <td>{this.state.username}</td>
        <td>{this.state.email}</td>
      </tr>
    </tbody>
    

    【讨论】:

    • 我试过了,但我遇到了一个错误。但我找到了解决方案。谢谢先生。
    【解决方案2】:

    你实际上只是保存状态一个元素,你应该保存状态数据的结果数组。

     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>
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2016-04-09
      • 2017-07-27
      • 2017-07-12
      • 1970-01-01
      • 2019-01-06
      • 2018-02-28
      • 2012-10-03
      • 1970-01-01
      相关资源
      最近更新 更多