Javascript Axios:获取特定用户的数据
我的React文件中有以下钩子:Javascript Axios:获取特定用户的数据,javascript,php,reactjs,laravel,axios,Javascript,Php,Reactjs,Laravel,Axios,我的React文件中有以下钩子: const [List, setList] = React.useState([]); useEffect(() => { axios .get("http://localhost:8000/api/profile/") .then((response) => { setList(response.data); con
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>
{List.map((项目,索引)=>{
如果(
item.user_id===user.id//Line,获取所有数据后,根据user.id显示数据
) {
返回(
-
{item.username}
);
}
返回null;
})}
我的问题是,我如何发送带有用户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}
)很难说,因为我们不知道您使用的API。路径、查询、主体参数?@jornsharpe这是由laravel生成的api。不过,这并没有告诉我们实际的接口是什么。一旦您发现,Axios文档将显示一系列请求。@jonrsharpe抱歉,我不理解您的问题。什么是api获取详细信息用户信息?Hokmat Abu Hmiad是的,我的api是rest,它是用Laravel创建的。但由于某些原因,您的代码似乎不起作用。您需要验证它。您的api是为允许您从特定用户获取数据而构建的,您需要验证路径,就像最后一个选项一样,如果它不存在,那么您需要先实现api或尝试查找它的api文档…get({userId})…我的api运行良好,我与POSTMAN一起测试过。但是当直接在postman中测试你的链接时,它不起作用。你能在这里共享你的postman url吗?你还可以选择导出js或curl之类的api代码…这也会很有帮助…api在你的机器上本地运行,我们无法向它发出请求。。。