【发布时间】:2021-06-03 21:48:51
【问题描述】:
javascript/react 新手在这里。我正在尝试使用来自 api 的数据从 Bootstrap 填充表。我制作了两个组件 - Dashboard.js 和 CustomTable.js,它们都具有功能性。据我所知,在仪表板组件上,我需要进行 API 调用——我已经使用 useEffect 和 axios 完成了。在 CustomTable.js 上,我需要对列和数据使用 useState。我想让我的表格动态,包括行和列。看看我的 Dashboard.js 代码。
const Dashboard = (props) => {
let state = [(columns: []), (data: [])];
useEffect(() => {
axios
.get(`https://reqres.in/api/users?page=2`)
.then((res) => {
console.log(res);
setData(res.data);
})
.catch((err) => {
console.log(err);
});
}, [data]);
return (
<div className="dashboard-content">
<Header />
<NewMessage />
<CustomTable data={data} columns={columns} />
</div>
);
};
接下来,我得到了我的 CustomTable.js 功能组件,我尝试从 Parent(Dashboard.js) 组件传递道具,但我不知道下一步该去哪里。
export default function CustomTable(props) {
const [data, setData] = useState(props.data);
const [columns, setColumns] = useState(props.columns);
return (
<div>
<Table striped bordered hover>
<thead>
<tr>
{columns.map((row) => {
return <th>{row.name}</th>;
})}
</tr>
</thead>
<tbody>
{data.map((row) => {
return (
<tr>
<td>{row.id}</td>
<td>{row.email}</td>
<td>{row.first_name}</td>
<td>{row.last_name}</td>
</tr>
);
})}
</tbody>
</Table>
</div>
);
}
如果这一切听起来很愚蠢,我很抱歉,但我真的很想完成这项任务并继续学习。谢谢!
【问题讨论】:
-
你想用这段代码实现什么?
-
我想完成我的代码,该代码将使用来自 api 的数据填充表格。
-
那么你的代码现在打印了什么?
-
没什么。正如我所说,我不知道接下来要写什么。
-
您没有正确设置 dashboard.jsx 中的列和数据
标签: reactjs bootstrap-4 axios react-props react-functional-component