我正在将 Next.js 与上下文 API 和样式组件一起使用,但我似乎无法理解getStaticProps
在职的。
我读过其他帖子,他们经常谈论习俗_app
我确实有,但在使用 context API 之前我从未遇到过这个问题。我也尝试过getInitialProps
功能并且无济于事。
我还应该注意到,即使在不包含上下文包装器之后,我也没有得到函数的响应,所以我根本不知道该在哪里查看。
这是我的代码。你能看到发生了什么事吗?
import React from 'react';
import fetch from 'node-fetch';
export default function Header(props) {
console.log(props.hi);
return <div>Hey dis header</div>;
}
export async function getStaticProps(context) {
return {
props: {
hi: 'hello',
},
};
}
我尝试从该函数进行日志记录,但没有任何记录,所以我想问题是该函数由于某种原因没有运行。
这是我的习惯_app
file
import { GlobalContextWrapper } from 'context';
import Header from 'components/header/Header';
import App from 'next/app';
function MyApp({ Component, pageProps }) {
return (
<GlobalContextWrapper>
<Header />
<Component {...pageProps} />
<p>footer</p>
</GlobalContextWrapper>
);
}
MyApp.getInitialProps = async (appContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps };
};
export default MyApp;
这是我的上下文文件
import { useReducer } from 'react';
import initialState from './intialState';
import reducer from './reducer';
import GlobalStyle from '../GlobalStyle';
import theme from '../theme';
import { ThemeProvider } from 'styled-components';
export const GlobalContext = React.createContext();
export function GlobalContextWrapper({ children }) {
const [globalState, dispatch] = useReducer(reducer, initialState);
return (
<GlobalContext.Provider value={{ globalState, dispatch }}>
<GlobalStyle />
<ThemeProvider theme={theme}>{children}</ThemeProvider>
</GlobalContext.Provider>
);
}