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

Ber*_*ren 2 server-side-rendering next.js

我在 next.js 应用程序中使用 use-sse (服务器端渲染挂钩),但收到错误“水合时出错。因为错误发生在 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>
      );
}
Run Code Online (Sandbox Code Playgroud)

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

Eli*_*ock 5

这里提到的一种解决方案: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;
  }
Run Code Online (Sandbox Code Playgroud)

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

  • 这个解决方案不会禁用服务器端渲染吗?这个解决方案是否使 SEO 与渲染一个普通的 React 应用程序相同? (3认同)