【问题标题】:I want to log my data using getInitialProps() from next.js我想使用 next.js 中的 getInitialProps() 记录我的数据
【发布时间】:2020-11-11 11:06:28
【问题描述】:

我是 next.js 的新手并做出反应,我只想从这个免费的 api https://reqres.in/api/users?page=2 取回数据

index.js 组件

import UserList from "./userList";

export default function Home() {
  return (
    <div>
      <UserList></UserList>
    </div>
  );
}

用户列表组件:

const UserList = (data) => {
console.log(data);
return <div>test</div>;
};
UserList.getInitialProps = async () => {
  const resp = await fetch(`https://reqres.in/api/users?page=2`);
  const data = await resp.json();
  console.log(data);
  return { data };
};
export default UserList;

使用console.log(data) 没有任何作用,有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:
    import React, { useState, useEffect } from "react";
    
    function UserList() {
      const [data, setData] = useState("");
      const [loading, setLoading] = useState(false);
      useEffect(() => {
        getUsers();
      }, []);
      async function getUsers() {
        setLoading(true);
        fetch("https://reqres.in/api/users?page=2")
          .then((response) => response.json())
          .then((data) => {
            setData(data);
            setLoading(false);
            console.log(data);
          })
          .catch((error) => {
            console.log(error);
            setLoading(false);
          });
      }
    
      return <>{loading ? <div>...Data Loading.....</div> : <div>{<p> {data.page}</p>}</div>}</>;
    }
    
    export default UserList;
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2018-09-30
      • 2019-06-23
      • 1970-01-01
      • 2019-10-12
      相关资源
      最近更新 更多