【问题标题】:Dynamically Pass Component props in NextJs在 NextJs 中动态传递组件道具
【发布时间】: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 的用途。您是否尝试过使用getStaticPropsgetServerSideProps
  • 我使用了 getserversideprops 但没有按预期工作。 getstaticprops 在这种情况下是不可接受的。因为我不想创建构建时间。
  • 您查看过getServerSideProps 文档吗?这不是您从中返回数据的方式。
  • 我想你没有理解我的问题。我问我从 getServerSideProps 成功获取了页面上的一些数据。现在我想在 Index.variable 中注册这些数据并将其发送到 MyApp Component 。
  • 我的意思是你不需要那样传递数据。从getServerSideProps 返回的数据可通过访问pageProps 属性在custom _app 中获得。像示例一样从getServerSideProps返回数据,它将可用。

标签: reactjs next.js


【解决方案1】:

Next.js 不提供将“动态数据”附加到组件的机制。可能是因为这种方法提出了几个需要解决的问题。究竟应该获取哪些数据?什么时候?由什么组成?解决方法之一是将数据获取功能附加到页面:

Page.fetchData = async () => {
  // fetch data from api
}

然后在 _app.js 中解决:

const App = ({ Component, pageProps }) => {
  const [fetchedData, setFetchedData] = useState();

  useEffect(() => {
    Component.fetchData().then((resolvedData) => {
      setFetchedData(resolvedData);
    });
  }, [Component]);

  // do something with fetchedData
};

另一方面,您是否考虑过仅在页面内获取此数据并将其传递给树下的组件?

【讨论】:

  • 我喜欢这个解决方法。但我发现@juliomalvis 的答案更适用于我的情况。我可以通过 serverSideProps 发送数据。并在 pageProps 中捕获它。所以我不需要使用 Component.fetchData 再次调用相同的 API。
猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 2021-07-08
  • 2020-09-08
  • 1970-01-01
  • 2021-10-06
  • 2019-04-24
  • 2019-01-27
相关资源
最近更新 更多