它的返回类型'Element | undefined' 不是有效的 JSX 元素。类型“未定义”不可分配给类型“Element |” 无效的'

4YJ*_*4YJ 6 setinterval reactjs next.js

使用 setInterval,我制作了 3 秒后更改屏幕的效果,使其看起来像移动应用程序。\n当我将其应用于 app.tsx 时,发生了错误。

\n

登陆/index.tsx

\n
import React, { useRef, useEffect, useState } from "react";\nimport * as S from "./style";\n\nconst Landing = () => {\n   const [sec, setSec] = useState<number>(3);\n   const time = useRef<number>(3);\n   const timerId = useRef<any>(null);\n\n   useEffect(() => {\n      timerId.current = setInterval(() => {\n         setSec(time.current % 60);\n         time.current -= 1;\n      }, 1000);\n\n      return () => clearTimeout(timerId.current);\n   }, []);\n\n   useEffect(() => {\n      if (time.current == 0) {\n         clearInterval(timerId.current);\n      }\n   }, [sec]);\n\n   if (time.current == 3) {\n      return (\n         <>\n            <S.Positioner>\n               <S.Wrapper>\n                  <S.TextWrapper>\n                     <S.Text>Ayo The</S.Text>\n                     <S.Title>Pizza Here</S.Title>\n                  </S.TextWrapper>\n                  <S.Copyright>\xc2\xa9</S.Copyright>\n               </S.Wrapper>\n            </S.Positioner>\n         </>\n      );\n   }\n};\n\nexport default Landing;\n\n
Run Code Online (Sandbox Code Playgroud)\n

_app.tsx

\n
import React from "react";\nimport {Global} from "@emotion/react";\nimport {GlobalStyles} from "../style/GlobalStyle";\nimport Landing from "../components/Landing";\nimport Main from "../components/Main";\nimport Head from "next/head";\n\nconst MyApp = () => {\n   return (\n     <>\n        <Head>\n           <title>A-Pizza</title>\n           <link rel="shortcut icon" href="/favicon.ico"/>\n        </Head>\n        <Global styles={GlobalStyles}/>\n        <Landing/>\n        <Main/>\n     </>\n   )\n}\n\nexport default MyApp\n
Run Code Online (Sandbox Code Playgroud)\n

如果删除此代码,应用程序上的错误就会消失\n我该如何修复它?\nif (time.current == 3)

\n

_app.tsx 错误图像

\n

nul*_*ptr 13

您需要return nullreturn <></>万一time.current不是 3. 如果没有显式返回任何内容,JS 函数将返回未定义。Typescript 正在抱怨,因为undefined它不是有效的反应元素。


Jav*_*ies 5

返回 jsx 元素是强制性的,如果不是,那么你至少应该返回 null。

\n
if (time.current == 3) {\n   return (\n      <>\n         <S.Positioner>\n            <S.Wrapper>\n               <S.TextWrapper>\n                  <S.Text>Ayo The</S.Text>\n                  <S.Title>Pizza Here</S.Title>\n               </S.TextWrapper>\n               <S.Copyright>\xc2\xa9</S.Copyright>\n            </S.Wrapper>\n         </S.Positioner>\n      </>\n   );\n} else {\n   return null;\n}\n
Run Code Online (Sandbox Code Playgroud)\n