[英]NextJS - Passing client-side props from app.js to specific components
In traditional React, a common pattern is to define the Routers at the entry point, and pass whatever props you need to whichever component needs them, since they're all defined在传统的 React 中,一种常见的模式是在入口点定义路由器,并将所需的任何道具传递给需要它们的任何组件,因为它们都已定义
Eg,例如,
<Switch>
<Route exact path="/">
<Home prop1={prop1}/>
</Route>
<Route path="/about">
<About prop1={prop1} prop2={prop2}/>
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
</Switch>
It's not clear to me how to do this in NextJS.我不清楚如何在 NextJS 中执行此操作。 The entry point _app.js has a generic that's used for all components.
入口点 _app.js 有一个用于所有组件的泛型。 What would be the best way to pass prop1 to Home and About, but not Dashboard?
将 prop1 传递给 Home 和 About 的最佳方式是什么,而不是 Dashboard?
To be clear, these are client-side props, not server-side or static props需要明确的是,这些是客户端道具,而不是服务器端或 static 道具
You can use getStaticProps
, see the code below:您可以使用
getStaticProps
,请参见下面的代码:
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
// export this function from each page you want to pass props, in your
// case have this function on About, Home and Dashboard pages.
}
}
for more check this link: getStaticProps有关更多信息,请查看此链接: getStaticProps
You can pass page specific props in getServerSideProps like below您可以在 getServerSideProps 中传递页面特定的道具,如下所示
import { GetServerSideProps } from "next";
const PageA = () => {
}
export const getServerSideProps: GetServerSideProps = async (ctx) => {
return {
props: {
forbidden: true
}
}
}
export default PageA;
Then you can control that prop value in _app.js file and take action然后您可以在 _app.js 文件中控制该道具值并采取行动
const App = ({ Component, pageProps }) => {
if (pageProps.forbidden) {
return <Page403 />;
}
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
So, think reversely.所以,反过来想。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.