reactjs 错误:补水时出错,由于错误发生在Suspense边界之外,因此整个根目录将切换到客户端呈现

sd2nnvve  于 2023-05-06  发布在  React
关注(0)|答案(6)|浏览(204)

我正在使用Next.js制作网站,每次都会显示上述错误。
我不知道我的代码有什么问题。

const Login = () => {
  const [userMsg, setUserMsg] = useState("");
  const [email, setEmail] = useState("");
  const router=useRouter();

  const handleOnChangeEmail = (e) => {
    e.preventDefault();
    setUserMsg("");
    console.log("event", e);
    const email = e.target.value;
    setEmail(email);
  };
  const handleLoginWithEmail = (e) => {
    e.preventDefault();
    if (email) {
      if (IsEmail.validate(email)){
        router.push("/")
        
      }else{
        setUserMsg("Enter a valid email address")
      }
      
    } else {
      //show usermssg
      setUserMsg("Enter an email address");
    }
  };
  return (
    <div className="bg-[url('/static/bglg.jpg')] flex items-stretch flex-col h-screen w-full">
      <head>
        <title>NeoVest SignIn</title>
      </head>
      <header className="text-4xl px-10 py-2 font-black">
        <span className="text-indigo-700">NeoVest</span>
      </header>
      <div className="w-full max-w-xs m-auto bg-[#C9C9C9] rounded p-5 bg-opacity-50 border-gray-200">
        <header>
          <div className="text-indigo-700 font-black text-3xl py-2">
            <p>Sign In</p>
          </div>
        </header>
        <form className="py-5">
          <div>
            <label className="block mb-2 text-indigo-500" for="username">
              Email
            </label>
            <input
              className="w-full p-2 mb-6 text-indigo-700 border-b-2 border-indigo-500 outline-none focus:bg-gray-300"
              type="text"
              name="username"
              placeholder="Email Address"
              onChange={handleOnChangeEmail}
            />
            <div className="block mb-2 text-red-700">
              <p>{userMsg}</p>
            </div>
          </div>
          <div>
            <input
              className="w-full bg-indigo-700 hover:bg-pink-700 text-white font-bold py-2 px-4 mb-6 rounded"
              type="button"
              value="Submit"
              onClick={handleLoginWithEmail}
            />
          </div>
        </form>
      </div>
    </div>
  );
};

显示的另一个错误是由于一些悬念边界导致root切换到客户端渲染:
错误:补水时出错。由于错误发生在Suspense边界之外,因此整个根将切换到客户端渲染。
如果这些信息很重要,我也会使用Tailwind。

mrwjdhj3

mrwjdhj31#

如果你看一下控制台,你会看到一个警告。

Warning: validateDOMNesting(...): <head> cannot appear as a child of <div>

所以,要解决这个问题,你只需要将head移出div,并将其移动到另一个更高的组件。

e7arh2l6

e7arh2l62#

如果您在Chrome中遇到此警告:

>  `validateDOMNesting(...): <head> cannot appear as a child of <div>`

您的DOM树没有在浏览器中正确打印,一个或多个标记没有正确关闭。

nfs0ujit

nfs0ujit3#

时间和随机性是最常见的两个因素
Hydration errors - Text content does not match server-rendered HTML. #38263中所述
可能的解决方案是使用useEffect钩子

// Example component with an error
import React from "react";

const AllNames = ["Ali", "Elisa", "Bella", "Carmen"];

const RandomUniqueNames = Array.from({ length: 4 }).map((_, index) => {
  let randomIndex = Math.floor(Math.random() * AllNames.length);
  let name = AllNames[randomIndex];
  return {
    name,
  };
});

export default function ModernNames() {
  return (
    <div>
      <h1>ModernNames</h1>
      {RandomUniqueNames.map((name) => (
        <p>{name.name}</p>
      ))}
    </div>
  );
}

// Example solution
import React, { useState, useEffect } from "react";

const AllNames = ["Ali", "Elisa", "Bella", "Carmen"];

export default function ModernNames() {
  const [randomNames, setRandomNames] = useState([]);
  useEffect(() => {
    const RandomUniqueNames = Array.from({ length: 4 }).map((_, index) => {
      let randomIndex = Math.floor(Math.random() * AllNames.length);
      let name = AllNames[randomIndex];
      return {
        name,
      };
    });
    setRandomNames(RandomUniqueNames);
  }, []);
  return (
    <div>
      <h1>ModernNames</h1>
      {randomNames.map((name, index) => (
        <p key={index}>{name.name}</p>
      ))}
    </div>
  );
}
4xrmg8kj

4xrmg8kj4#

问题是这样的:

<head>
    <title>NeoVest SignIn</title>
</head>

要解决这个问题,首先导入Head,然后使用大写字母“H”

import Head from "next/head"

<Head>
    <title>NeoVest SignIn</title>
</Head>
vshtjzan

vshtjzan5#

我在代码中验证了一些主题。首先,验证next.config.js中是否声明了样式化组件。

reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },

第二步,我检查了文件babel“.babelrc”是否在根文件夹中创建了以下内容:

{
  "presets": ["next/babel"],
  "plugins": ["styled-components"]
}

错误还没有显示出来。我逐个检查组件,发现了两个以上的错误。首先,像这样的HTML错误:

<!-- wrong -->
<p>
<ul></ul>
</p>
<!-- right -->
<p></p>
<ul></ul>
<p></p>
<!-- or right -->
<div>
<ul></ul>
</div>

最后,我发现了一个初始化组件的错误。在我的例子中,我错误地声明了一个const items(object)。执行此操作的正确方法是使用useState。

<!-- WRONG WAY THAT I WAS DID -->
const Works = () => {
  const items =  [
    {
      id: 1,
      name: 'any name',
      src: 'srcpath'
    },
    {
      id: 2,
      name: 'any name 2',
      src: 'srcpath'
    },
    {
      id: 3,
      name: 'any name 3',
      src: 'srcpath'
    },
];

return(
   items.map((item, index) => {
     return(
        <div key={index}>{item.name}</div>
     )
   }
)
});

<!-- RIGHT WAY THAT I FIXED -->
const Works = () => {
  const [ item, setItem ] = React.useState();
  React.useEffect(() => {
     setItem([
    {
      id: 1,
      name: 'any name',
      src: 'srcpath'
    },
    {
      id: 2,
      name: 'any name 2',
      src: 'srcpath'
    },
    {
      id: 3,
      name: 'any name 3',
      src: 'srcpath'
    },
   ]);
  }, []);
  
if(item)
return(
   items.map((item, index) => {
     return(
        <div key={index}>{item.name}</div>
     )
   }
)
});
8qgya5xd

8qgya5xd6#

你可以尝试降级react版本。试试react@17

相关问题