[英]ReactJS + NextJS - How to pass props from _app.js to page?
[英]Pass data (prop) from _app.js to getServerSideProps in a page - NextJS, latest version
我有一个自定义_app.js
:
const Layout = ({ children }) => (children);
const app = ({ Component, pageProps }) => {
pageProps.baseUrl = 'some url';
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
};
还有一个页面:
export async function getServerSideProps({ req, query, res, baseUrl }) {
// baseUrl is undefined and an error, if I am using it with destructiring
console.log(req) // There is no baseUrl
return { props: { ..... } }
}
我想设置pageProps.baseUrl= 'some url';
在_app.js
中并在包括getServerSideProps
在内的页面组件中使用它,我该怎么做?
现在,我创建了一个文件,其中包含所有全局值,如下所示:
let store = {};
const globalStore = {};
globalStore.set = (key, value) => {
store = { ...store, [key]: value };
}
globalStore.get = (key) => {
return store[key];
}
export default globalStore;
然后在_app.js
中导入它并设置一个值:
const app = ({ Component, pageProps }) => {
globalStore.set('baseUrl', 'some url 1');
globalStore.set('baseUrl2', 'some url 2');
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
在pages/index.js
和组件或getServerSideProps
中导入文件:
export async function getServerSideProps({ req, query, res }) {
console.log('in getServerSideProps');
console.log(globalStore.get('baseUrl'));
console.log(globalStore.get('baseUrl2'));
...
我认为,在这种特殊情况下,可以在这里使用常量而不是道具。
在常量.js 中:
export const BASE_URL = 'some url';
在您的页面中:
import * as Constants from '../path/to/constants';
export async function getServerSideProps({ req, query, res }) {
// use Constants.BASE_URL here
return { props: { ..... } }
}
您的页面组件和您从文件中导出的 getServerSideProps 方法是分开的,并且在不同的时间执行。 渲染组件不会调用 getServerSideProps。 我相信 Next.js 中的顺序是这样的:
pages/
中的文件寻找对应的路由在这种情况下,你创造了一个悖论。 想想道具是如何流动的:
如果 getServerSideProps 负责创建 pageProps object,也不能将 object 作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.