首页 > 解决方案 > 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 请求,然后显示该用户的数据,而不是获取服务器的所有数据并对其进行过滤?

标签: javascriptphpreactjslaravelaxios

解决方案


您可以通过将参数添加到 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})


推荐阅读