简体   繁体   English

NextJS如何在点击事件后获取数据?

[英]NextJS how to fetch data after click event?

I have problem with load data to component after click on button.单击按钮后,我在将数据加载到组件时遇到问题。 I use getInitialProps to first load data on page.我使用getInitialProps首先在页面上加载数据。

How to load new data and past them to {data} after click?点击后如何加载新数据并将其传递给{data}

export default function Users({ data }) {
  const fetchData = async () => {
    const req = await fetch("https://randomuser.me/api/?gender=male&results=100");
    const data = await req.json();

    return { data: data.results };
  };
  const handleClick = (event) => {
    event.preventDefault();

    fetchData();
  };
  return (
    <Layout>
      <button onClick={handleClick}>FETCH DATA</button>
      {data.map((user) => {
        return (
          <div>
            {user.email}
            <img src={user.picture.medium} alt="" />
          </div>
        );
      })}
    </Layout>
  );
}

Users.getInitialProps = async () => {
  const req = await fetch(
    "https://randomuser.me/api/?gender=female&results=10"
  );
  const data = await req.json();
  return { data: data.results };
};

Thank a lot for help!非常感谢您的帮助!

Use useState with the default value being the data you initially retrieved via getInitialProps :使用useState ,默认值是您最初通过getInitialProps检索到的数据:

import { useState } from 'React';

export default function Users({ initialData }) {
    const [data, setData] = useState(initialData);

    const fetchData = async () => {
        const req = await fetch('https://randomuser.me/api/?gender=male&results=100');
        const newData = await req.json();

        return setData(newData.results);
    };

    const handleClick = (event) => {
        event.preventDefault();
        fetchData();
    };

    return (
        <Layout>
            <button onClick={handleClick}>FETCH DATA</button>
            {data.map((user) => {
                return (
                    <div>
                        {user.email}
                        <img src={user.picture.medium} alt="" />
                    </div>
                );
            })}
        </Layout>
    );
}

Users.getInitialProps = async () => {
    const req = await fetch('https://randomuser.me/api/?gender=female&results=10');
    const data = await req.json();
    return { initialData: data.results };
};

Sidenote: Times have changed and it would seem that user1665355 is indeed correct:旁注: 时代变了,看来user1665355确实是正确的:

Recommended: getStaticProps or getServerSideProps推荐: getStaticPropsgetServerSideProps

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps .如果您使用的是 Next.js 9.3 或更高版本,我们建议您使用getStaticPropsgetServerSideProps而不是getInitialProps

These new data fetching methods allow you to have a granular choice between static generation and server-side rendering.这些新的数据获取方法允许您在 static 生成和服务器端渲染之间进行精细选择。

It is recommended to use getStaticProps or getServerSideProps now.建议现在使用 getStaticProps 或 getServerSideProps。 https://nextjs.org/docs/api-reference/data-fetching/getInitialProps https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

import { useState } from 'React';

export default function Users({ initialData }) {
  const [data, setData] = useState(initialData);

  const fetchData = async () => {
    const req = await fetch('https://randomuser.me/api/?gender=male&results=100');
    const newData = await req.json();

    setData(newData.results);
  };

  const handleClick = (event) => {
    event.preventDefault();
    fetchData();
  };

  return (
    <Layout>
      <button onClick={handleClick}>FETCH DATA</button>
      {data.map(user => {
        return (
          <div key={user.login.uuid}>
            {user.email}
            <img src={user.picture.medium} alt="" />
          </div>
        );
      })}
    </Layout>
  );
}

Users.getInitialProps = async () => {
  const req = await fetch('https://randomuser.me/api/?gender=female&results=10');
  const data = await req.json();
  
  return { initialData: data.results };
};

I would like to list my notes about George's code.我想列出我对 George 代码的注释。 At least, it should pay attention to them.至少,它应该注意它们。

First of all, it should attach any key to a div element otherwise a warning will have appeared in the browser console.首先,它应该将任何键附加到 div 元素,否则浏览器控制台中会出现警告。 Here is an article about using keys: https://reactjs.org/docs/lists-and-keys.html#keys这是一篇关于使用密钥的文章: https://reactjs.org/docs/lists-and-keys.html#keys

As well, the keyword return can be removed from the fetchData function that doesn't return a response.同样,关键字return可以从不返回响应的fetchData function 中删除。

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

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