繁体   English   中英

我想使用 next.js 中的 getInitialProps() 记录我的数据

[英]I want to log my data using getInitialProps() from next.js

我是 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)不做任何事情,有什么帮助吗?

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM