使用API数据在React.js中创建React表
我以前已经看到了一些使用API数据创建React表的示例,但是没有人使用API数据中的标头(键)将标题设置为React Table中的标题。请有人帮我这样做。
在我的代码中,我从数组中的API数据中提取了标题。然后,我需要将这些值作为标题和登录器值传递。但是我不明白该怎么做。
这是api = https://reqres.in/api/api/users?page=1
I am fetching data from this Axios API in a hook :
import axios from 'axios';
let userRole;
const [userData, setUserData] = useState({});
useEffect(()=>{
axios.get(`https://reqres.in/api/users?page=1`)
.then(res => {
userRole = res.data.data;
console.log("Data from API",userRole);
userRole.sort((a,b) => a.first_name.localeCompare(b.first_name) )
setUserData(userRole);
});
}, []);
//console.log(userData);
API Data from UserRole looks like this : 在此处输入图像描述
let headerList = [];
function BasicTableComponent() {
//console.log("Full data in array",userData)
// EXTRACT VALUE FOR HTML HEADER.
for (var i = 0; i < userData.length; i++) {
for (var key in userData[i]) {
if (headerList.indexOf(key) === -1) {
headerList.push(key);
}
}
}
console.log("Column Header List check",headerList);
/*Now instead of this hardcoded method I want to pass values
from my headerList for Header and accessor in my columns.*/
const columns = React.useMemo(
() => [
{
Header: 'Column 1',
accessor: 'col1', // accessor is the "key" in the data
},
{
Header: 'Column 2',
accessor: 'col2',
},
],
[]
)
//console.log("Column Header",columns)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, userData })
return (
<table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th
{...column.getHeaderProps()}
style={{
borderBottom: 'solid 3px red',
background: 'aliceblue',
color: 'black',
fontWeight: 'bold',
}}
>
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td
{...cell.getCellProps()}
style={{
padding: '10px',
border: 'solid 1px gray',
background: 'papayawhip',
}}
>
{cell.render('Cell')}
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
)
}
I have seen some examples of creating react tables using API data before but no one used the header(key) from API data to set headers in react table. Please someone help me to do this.
In my code, I have extracted headers from API data in an array. Then I need to pass that values in columns as Headers and accessor values. But I don't understand how to do that.
Here's the API = https://reqres.in/api/users?page=1
I am fetching data from this Axios API in a hook :
import axios from 'axios';
let userRole;
const [userData, setUserData] = useState({});
useEffect(()=>{
axios.get(`https://reqres.in/api/users?page=1`)
.then(res => {
userRole = res.data.data;
console.log("Data from API",userRole);
userRole.sort((a,b) => a.first_name.localeCompare(b.first_name) )
setUserData(userRole);
});
}, []);
//console.log(userData);
API Data from UserRole looks like this :
enter image description here
let headerList = [];
function BasicTableComponent() {
//console.log("Full data in array",userData)
// EXTRACT VALUE FOR HTML HEADER.
for (var i = 0; i < userData.length; i++) {
for (var key in userData[i]) {
if (headerList.indexOf(key) === -1) {
headerList.push(key);
}
}
}
console.log("Column Header List check",headerList);
/*Now instead of this hardcoded method I want to pass values
from my headerList for Header and accessor in my columns.*/
const columns = React.useMemo(
() => [
{
Header: 'Column 1',
accessor: 'col1', // accessor is the "key" in the data
},
{
Header: 'Column 2',
accessor: 'col2',
},
],
[]
)
//console.log("Column Header",columns)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, userData })
return (
<table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th
{...column.getHeaderProps()}
style={{
borderBottom: 'solid 3px red',
background: 'aliceblue',
color: 'black',
fontWeight: 'bold',
}}
>
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td
{...cell.getCellProps()}
style={{
padding: '10px',
border: 'solid 1px gray',
background: 'papayawhip',
}}
>
{cell.render('Cell')}
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的理解,您正在寻求创建具有两个属性的对象。一个是“列名”,将用作表格中的标头,第二个是“键”,用于访问“ UserData”的值。
我已经修改了使用效果以检索数据,设置UserData并设置列。
由于您希望列保存动态数据,因此我将该部分放置在使用效果中,因为它取决于我们从API中检索的数据。抱歉,没有正确格式化代码。
As per my understanding, you are looking to create an array of objects that has two properties. One is 'column name' that is going to be used as header in the table and the second is 'key' that is used to access the value from 'userData'.
I have modified useEffect to retrieve data, set userData and set columns.
Since you want columns to hold dynamic data, I have placed that part inside useEffect because it is dependent on the data that we retrieve from API. Sorry for not formatting code properly.