简体   繁体   English

如何使用 reactjs 将数据呈现为 intable

[英]how to render data intable using reactjs

i am trying to display data in table fornmat.我正在尝试以表格格式显示数据。 Data is coming from an api.数据来自 api。 i need to display table once data recived from api.从 api 收到数据后,我需要显示表格。 i am using class component .我正在使用class 组件 below i have given what is tried.下面我给出了尝试过的内容。

//below is my jsx //下面是我的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>

//below is my function to get data from api //下面是我的 function 从 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);
                            });
                        };

//below is my api output //下面是我的 api output

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

You can iterate over when the data came into HTML elements:当数据进入 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>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM