4YJ*_*4YJ 6 setinterval reactjs next.js
使用 setInterval,我制作了 3 秒后更改屏幕的效果,使其看起来像移动应用程序。\n当我将其应用于 app.tsx 时,发生了错误。
\n登陆/index.tsx
\nimport 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
\nimport 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)
nul*_*ptr 13
您需要return null
或return <></>
万一time.current
不是 3. 如果没有显式返回任何内容,JS 函数将返回未定义。Typescript 正在抱怨,因为undefined
它不是有效的反应元素。
返回 jsx 元素是强制性的,如果不是,那么你至少应该返回 null。
\nif (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
归档时间: |
|
查看次数: |
21418 次 |
最近记录: |