我正在尝试将 API 响应加载到 Next.js 页面中,但道具返回未定义。我从 StackOverflow 得到了很多答案,但仍然找不到解决我的问题的方法。
编辑此帖子添加了更多详细信息以获取支持。
下面是我的代码。
_app.tsx
import 'tailwindcss/tailwind.css';
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { UserProvider } from '@auth0/nextjs-auth0';
import App from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
return {...appProps};
}
export default MyApp
个人资料.tsx
import React from 'react';
import { useUser } from '@auth0/nextjs-auth0';
import withAuth from '../components/withAuth';
import { Navbar } from '../components/navbar'
import styles from '../styles/Home.module.css'
import type { GetStaticProps, NextPage } from 'next';
export const getStaticProps: GetStaticProps = async(context) =>{
// const res = await fetch(`http://localhost:3000/api/users`);
const data = "sed"
console.log(data);
return {
props: {
users:data
}
}
}
const Profile: NextPage<{users:any}> = ({users}) => {
const {user, isLoading} = useUser();
console.log(users);
return (
<>
<Navbar />
<div className={styles.container}>
<div>profile</div>
</div>
</>
)
}
export default withAuth(Profile);
这是登录后为每个页面包装的 HOC 代码。
withAuth.tsx
import Login from "../pages/login";
import { Spinner } from "./spinner";
const withAuth = Component => {
const Auth = (props) => {
const { isLoggedIn, loading } = props;
if(loading){
return (
<Spinner />
)
}
if (!isLoggedIn) {
return (
<Login />
);
}
// If user is logged in, return original component
return (
<Component {...props} />
);
};
if (Component.getInitialProps) {
Auth.getInitialProps = Component.getInitialProps;
}
return Auth;
};
export default withAuth;