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

时间:2020-06-14 12:25:04

标签: reactjs next.js

单击按钮后,我无法将数据加载到组件。 我使用getInitialProps首先在页面上加载数据。

如何在单击后加载新数据并将其粘贴到{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 };
};

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

使用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 };
};

旁注:Times have changed,看来user1665355确实是正确的:

推荐:getStaticPropsgetServerSideProps

如果您使用的是Next.js 9.3或更高版本,我们建议您使用 getStaticPropsgetServerSideProps而非getInitialProps

这些新的数据获取方法使您可以进行精细选择 在静态生成和服务器端渲染之间。

答案 1 :(得分:0)

建议立即使用getStaticProps或getServerSideProps。 https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

答案 2 :(得分:0)

getElementById

我想列出我有关George代码的注释。至少应该注意它们。

首先,它应该将任何键附加到div元素上,否则浏览器控制台中将出现警告。这是有关使用键的文章:https://reactjs.org/docs/lists-and-keys.html#keys

同样,可以从不返回响应的mAuth.createUserWithEmailAndPassword(email, pwd) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { Toast.makeText(RegisterActivity.this,"Authentication Failed!",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(RegisterActivity.this,"You have registered!",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this,HomeActivity.class); startActivity(intent); } } }); 函数中删除关键字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 }; };