【发布时间】:2022-01-19 20:24:37
【问题描述】:
我有一个像下面这样的组件表单 -
const MyApp = ({ Component, pageProps, getReqCookie }) => {
const variable = Component.variable;
console.log(variable)
}
const Index = () => {
}
Index.variable = "something"
目前像这样将静态变量传递给 MyApp。但是如何将这个变量动态传递给我的 MyApp?
该变量应加载 API 数据并将其传递给 MyApp 组件。
例子:
Index.variable = {fetched data from api}
我使用了 getserverSideprops 并初始化了其中的数据。但不工作。
export const getServerSideProps = async () => {
const data = fetched from API
Index.variable = data;
}
【问题讨论】:
-
“该变量应该加载 API 数据并将其传递给 MyApp 组件。” - 这就是 Next.js data fetching methods 的用途。您是否尝试过使用
getStaticProps或getServerSideProps? -
我使用了 getserversideprops 但没有按预期工作。 getstaticprops 在这种情况下是不可接受的。因为我不想创建构建时间。
-
您查看过
getServerSideProps文档吗?这不是您从中返回数据的方式。 -
我想你没有理解我的问题。我问我从 getServerSideProps 成功获取了页面上的一些数据。现在我想在 Index.variable 中注册这些数据并将其发送到 MyApp Component 。
-
我的意思是你不需要那样传递数据。从
getServerSideProps返回的数据可通过访问pageProps属性在custom_app中获得。像示例一样从getServerSideProps返回数据,它将可用。