【问题标题】:how to render data intable using reactjs如何使用 React js 在表格中呈现数据
【发布时间】:2021-04-17 23:39:29
【问题描述】:

我正在尝试以表格格式显示数据。数据来自 api。从 api 接收数据后,我需要显示表格。我正在使用 类组件 。下面我给出了尝试的内容。

//下面是我的jsx

             <div>
                <input onChange={this.handleSearchChange} placeholder="Search" />
                <div>
                    if (!this.state.user.length) return <div>No data</div>
                    <table>
                    <thead>
                        <th>Color</th>
                        <th>Name</th>
                        <th>Age</th>
                    </thead>
                    <tbody> </tbody>
                    </table>
                </div>
             </div>

//下面是我从api获取数据的函数

                        handleSearchChange = (e) => {
                            const { value } = e.target;
                            var self = this;
                            axios
                            .post("http://localhost:3000/user", { namr: value })
                            .then(function (res) {
                                this.setState({ user: res.data }); // Error TypeError: Cannot read property 'setState' of undefined
                            })
                            .catch(function (err) {
                                console.log("Error", err);
                            });
                        };

//下面是我的api输出

                    [
                        {color: "green",name: "test",age: "22"},
                        {color: "red",name: "test2",age: "23"}
                    ]

【问题讨论】:

    标签: javascript node.js reactjs html-table


    【解决方案1】:

    您可以在数据进入 HTML 元素时进行迭代:

    <table>
      <thead>
        <th>Color</th>
        <th>Name</th>
        <th>Age</th>
      </thead>
      <tbody>
        {user.map(userData => (
          // A unique key for each element
          <tr key={userData.name}>
            <td>{userData.name}</td>
            <td>{userData.color}</td>
            <td>{userData.age}</td>
          </tr>
        ))}
      </tbody>
    </table>;
    

    【讨论】:

    • no.. 实际上它在 setstate() 中给出错误。
    • @kp987987 这是另一个问题;你应该在.then() 中使用箭头函数
    猜你喜欢
    • 2018-06-09
    • 2020-11-08
    • 2021-02-16
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2022-11-03
    相关资源
    最近更新 更多