gpt4 book ai didi

reactjs - Nextjs 和 Context API

转载 作者:行者123 更新时间:2023-12-03 13:42:43 27 4
gpt4 key购买 nike

使用 Next.js,在 getInitialProps 中获取数据后,我尝试将数据保存在 Context API 状态中,以修复 props 钻取问题。

但是由于getInitialProps是一个静态方法,我们无法通过this.context访问它。我设法将它们保存在 componentDidMount 中,但在这种情况下,上下文状态在第一页加载时为空,直到它填充为止。不确定在这种情况下最佳实践是什么。我应该在哪个生命周期中将初始数据保存到 Context 以便像 props 传递一样立即获得它们?

最佳答案

you cannot use ContextAPI in Next.js server-side (SSR), because it's against hooks rules. https://reactjs.org/warnings/invalid-hook-call-warning.html

React 将首先运行 getInitialProps,因此最好的解决方案是从其中获取数据并使用 ContextAPI 将其传递到您的组件。

让我们继续看看它的工作原理如下:

创建您的 AppProvider 组件

实现您想要通过 React 组件传递的上下文提供程序函数。

对于这种情况,我们将创建全局上下文提供程序,将整个应用程序包装在其中。

const AppProvider = ({ children }) => {
const [galleryData, setGalleryData] = React.useState([]);

const handleGalleryData = galleryData => {
setGalleryData(galleryData);
}

const contextProps = {
galleryData,
handleGalleryData
};

return (
<AppContext.Provider value={contextProps}>
{children}
</AppContext.Provider>
);
}

然后使用这个新的提供程序包装您的应用。

<AppProvider>
<App />
</AppProvider>

进入您的页面,例如 index.js,请尝试以下方式:

Index.getInitialProps = async (props) => {
const { req, res, query, ...others } = props;

// use your env variables, endpoint URIs
// ..

... fetch whatever you want..
const galleryProps = await fetch(endpoint); // isomorphic-unfetch

return {
galleryProps,
query,
...others
};
}

根据您的 Next.js 版本,您可以使用 getServerSideProps 而不是 getInitialProps,但请注意每个请求都会调用它。

Next.js will pre-render this page on each request using the data returned by getServerSideProps Data Fetching docs

开始在您的组件上使用 ContextAPI

然后在您的组件中,您可以检查此数据并将其存储到 ContextAPI

const Index = props => {
const { galleryProps, query, ...others } = props;
const [galleryData, setGalleryData] = useState(galleryProps);
const { handleGalleryData, ...contextRest } = useContext(AppContext);
...

// Here you're going to store data into ContextAPI appropriatly.
useEffect(() => {
if (typeof galleryProps === 'object' && _.keys(galleryProps).length > 0) {
handleGalleryData(galleryProps);
}
}, [handleGalleryData]);

// Other times your page is loaded, you will GET this data from ContextAPI, instead of SSR props.
useEffect(() => {
if (_.keys(galleryDataProps).length <= 0 && _.keys(contextRest.galleryData).length > 0) {
setGalleryData(contextRest.galleryData);
}
}, []);

....

return (
<div>
{JSON.stringify(galleryData)}
</div>
);

上面的用例不是最好的用例,但它让我们了解了 Next.js 应用程序中的 ContextAPI 是如何工作的。我将在下面解释它:

  • 第一个 useEffect() 正在验证组件是否从通过 ContextAPI 存储数据的 props 接收到数据对象。

  • 第二个检查商店是否获得了一些数据

You may fetch data in SSR mode over getInitialProps before your component loads.

引用文献

关于reactjs - Nextjs 和 Context API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com