如何在 Next.js 页面中设置 pageProps 属性?

cla*_*ine 5 javascript reactjs next.js

考虑.../pages/_app.js中的以下代码,组件是从当前页面导出的组件。

因此,假设您访问https://yourdomain.com/about , .../pages/about.js中导出的组件将是Component中的值将是.../pages/_app.js

现在,当您通过控制台记录 pageProps 时,会显示一个空对象。

我的问题是如何在.../pages/about.js中设置 pageProps 值。

.../pages/about.js

const About = () => {
 return <p>About Page</p>
}

export default About
Run Code Online (Sandbox Code Playgroud)

.../pages/_app.js

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp
Run Code Online (Sandbox Code Playgroud)

小智 6

如何在 Next.js 页面中设置 pageProps 属性

getStaticProps当您使用或获取数据getServerSideProps时,您传递propsie 可能是来自 api call 的数据。然后你将它传递props给你的Page Component. 该 props 表示pageProps 为_app.js。

在您的代码中,您尚未使用数据获取getStaticProps或getServerSideProps将函数的返回值传递为props。所以你得到的空对象是pageProps

const About = () => {
 return <p>About Page</p>
}

export default About
Run Code Online (Sandbox Code Playgroud)

下面todos作为 props 传递给Page Component. 当你console.log(pageProps)这样做_app.js时你会得到api call result as pageProps


export default function IndexPage(props) {
  return (
    <div>
      Todos list
      <ul>
        {props.todos.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
}

export async function getServerSideProps() {
  const todos = await fetch(
    "https://jsonplaceholder.typicode.com/todos"
  ).then((response) => response.json());

  return {
    props: { todos }
  };
}

Run Code Online (Sandbox Code Playgroud)

沙盒链接