简体   繁体   English

React Next.js 不在生产应用程序中调用 useEffect 钩子

[英]React Next.js not calling useEffect hook in production app

I have a decently large Next.js/React application.我有一个相当大的 Next.js/React 应用程序。 A few days ago, some pages which worked flawlessly before, started behaving weirdly - more specifically, some Axios requests inside of a useEffect hook stopped being sent at all.几天前,一些以前完美无缺的页面开始出现奇怪的行为 - 更具体地说, useEffect钩子内的一些 Axios 请求useEffect停止发送。

More details:更多细节:

This is the file which is causing the bugs:这是导致错误的文件:

export const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [auth, setAuth] = useState(null);

  useEffect(async () => {
    const { data: result } = await axiosApp.get("/auth-status"); // axiosApp = same thing as axios
    setAuth(result);
  }, []);

  return !auth ? (
    <div className="pretend-this-is-a-progress-bar"></div>
  ) : (
    <AuthContext.Provider value={[auth, setAuth]}>{children}</AuthContext.Provider>
  );
}

As you can see I'm using react context here for the authentication in my app.正如您所看到的,我在此处使用 react 上下文在我的应用程序中进行身份验证。 This component here is located in the _app.js file, and the different next.js pages are passed as children of the <ContextProvider/> .这里的这个组件位于_app.js文件中,不同的 next.js 页面作为<ContextProvider/>子元素传递。

As you can also see, this file sends a request to auth-staus in it's useEffect hook, which tells the app whether the user is logged in or not.正如您还看到的,这个文件在它的useEffect钩子中向auth-staus useEffect发送一个请求,它告诉应用程序用户是否登录。 The problem is, and I found this only occurs in pages that have a getServerSideProps function, and only in production using a production build , that this request is simply not sent.问题是,我发现这仅发生在具有getServerSideProps函数的页面中,并且仅在使用生产构建的生产中发生,该请求根本不会发送。 What ends up happening is the auth state stays at null which in the end leads to the page loading infinitely for the user.最终发生的是auth状态保持为null ,这最终导致页面为用户无限加载。

Why is this happening, and what can I do to solve this bug?为什么会出现这种情况,我能做些什么来解决这个错误?

PS : I will gladly provide any other info you need to answer this EDIT : I know the request isn't sent because it doesn't appear in the console's network tab PS :我很乐意提供你需要的任何其他信息来回答这个编辑:我知道请求没有发送,因为它没有出现在控制台的网络选项卡中

It is not recommended to use async in useEffect callback like @Dimitri said.不建议像@Dimitri 所说的那样在useEffect回调中使用 async。 Try something like this.尝试这样的事情。

 export const AuthContext = createContext(); export function AuthProvider({ children }) { const [auth, setAuth] = useState(null); useEffect(() => { async function fetchAuthStatus() { const { data: result } = await axiosApp.get("/auth-status"); // axiosApp = same thing as axios setAuth(result); } fetchAuthStatus(); }, []); return !auth ? ( <div className="pretend-this-is-a-progress-bar"></div> ) : ( <AuthContext.Provider value={[auth, setAuth]}>{children}</AuthContext.Provider> ); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM