next.js - 使用 use-sse 时,有什么方法可以克服 next.js 中水合 UI 的错误吗?

标签 next.js server-side-rendering

我在 next.js 应用程序中使用 use-sse(服务器端渲染 Hook ),但收到错误“水合时发生错误。因为错误发生在 Suspense 边界之外,所以整个根将切换到客户端渲染。” 代码都类似于链接 https://github.com/kmoskwiak/useSSE 。不幸的是,我无法预测 next.js 应用程序中的水合错误。这里面有什么问题吗? 这是代码:

import { useSSE } from "use-sse";
import React from 'react';

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

export default function Todo() {
    const [todos, error] = useSSE(() : Promise<Todo[]>=> {
      
        return fetch("https://jsonplaceholder.typicode.com/todos").then(
          (response: Response) => response.json()
        );
       
      }, []);
      console.log(todos);
      if (error) return <div>{error.message}</div>;
    
      if (!todos?.length) return <span>Todo is Loading...</span>;
    
      return (
        <section>
          <h1>Todo List</h1>
          <ul>
            {todos.map((todo: Todo) => {
              return (
                <li key={todo.id}>
                  <h6>{todo.title}</h6>
                </li>
              );
            })}
          </ul>
        </section>
      );
}

它现在甚至没有检测到 use-sse 包。还有其他方法可以使用这个钩子(Hook),即 use-sse 吗?

最佳答案

此处记录了一个解决方案:https://www.joshwcomeau.com/react/the-perils-of-rehydration/#the-solution

  const [hasMounted, setHasMounted] = React.useState(false);
  React.useEffect(() => {
    setHasMounted(true);
  }, []);
  if (!hasMounted) {
    return null;
  }

这也可能有帮助:https://nextjs.org/docs/messages/react-hydration-error

关于next.js - 使用 use-sse 时,有什么方法可以克服 next.js 中水合 UI 的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72220011/

相关文章:

javascript - Next.js with Auth0 (using Passport.js) on Serverless Function

reactjs - 使用 react 和 SSR 增加元素 Id (next.js)

javascript - Sveltekit 从静态文件夹中获取文件

javascript - 如何将数据从组件传递到 getServerSideProps

aws-lambda - next-i18next 的错误和在 Vercel 上的部署(最近)

javascript - 有没有办法从 NextJS API 路由读取 getStaticProps 的输出?

reactjs - 调用 mutate 时 SWR 不重新渲染

node.js - 如何通过apache连接 Node 服务器?

reactjs - 使用动态路由、next JS 和 useEffect 在 React 中获取数据

reactjs - 在 next.js 中使用 getStaticProps() 时获取未定义的数据