javascript - axios:获取特定用户的数据
问题描述
我的 React 文件中有以下钩子:
const [List, setList] = React.useState([]);
useEffect(() => {
axios
.get("http://localhost:8000/api/profile/")
.then((response) => {
setList(response.data);
console.log(response);
})
.catch((err) => console.log(err));
}, []);
它获取整个数据库的所有配置文件。然后我根据user.id
具体用户的数据显示:
<ul>
<div>
{List.map((item, index) => {
if (
item.user_id === user.id // Line where I'm displaying data according to the user.id after fetching all data
) {
return (
<li key={item.id}>
<div>
{item.username}
</Link>
</div>
</li>
);
}
return null;
})}
</div>
</ul>
我的问题是,如何使用 user_id 发送自定义 axios 请求,然后显示该用户的数据,而不是获取服务器的所有数据并对其进行过滤?
解决方案
您可以通过将参数添加到 get 方法来做到这一点,例如:
useEffect(() => {
axios
.get("http://localhost:8000/api/profile/", {
"user_id": yourUserId
})
.then((response) => {
setList(response.data);
console.log(response);
})
.catch((err) => console.log(err));
}, []);
了解更多详情
注意:您的 api 必须是 rest 并允许您通过用户 id 获取用户数据,或者如果它在路径中,您只需要添加它:axios
.get( http://localhost:8000/api/profile/${userId}
)
推荐阅读
- xcode12 - Xcode 12 中缺少工作区配置按钮
- nginx - Nginx rewrite-target 将 domain/suffix/index.php 覆盖为 domain/index.php
- excel - 在 Google Sheets 或 Excel 上搜索多个 Vlook up 列或索引
- docker - 在 GitLab CI/CD 中构建/测试/部署 docker 映像的首选方式
- java - java - 如何在java servlet中正确使用guice进行依赖注入?
- grid - w2ui 网格内联编辑(日期范围验证)
- c# - 可编辑的 DataGridView - 检测新行和已编辑的行,并做出相应的响应
- angular - 如果我在 Angular 中切换切换,则计算下拉列表的值
- c - 关于 glVertexAttribPointer 索引参数的说明
- powershell - Out-GridView 中的重复结果 [在此对象上找不到属性“已安装”。验证该属性是否存在并且可以设置。]?