React 中的 setInterval 错误

这个案子有什么问题。我想显示一个随机名称并每 2 秒更改一次,但几秒钟后它会不断变化,即使我清理 setName 时名称也会被覆盖?


import React, {useState} from "react";

import "./styles.css";


export default function App() {

  const [name, setName] = useState();

    const arrayName = ['Tom','Alice','Matt','Chris'];

  

    const nameChange = () => {

        const rand = Math.floor(Math.random()*arrayName.length);

        setName(arrayName[rand])   

    }

    setInterval(()=>{ 

        setName('');

        nameChange();

        console.log(name);

    }, 2000)

  return (

    <div className="App">

      <h1>Hello {name}</h1>


    </div>

  );

}


HUH函数
浏览 140回答 3
3回答

慕妹3146593

它会在您的组件每次渲染时创建一个新的间隔,这会导致它再次渲染并最终导致无限循环。尝试这个:import React, {useState, useEffect, useCallback} from "react";import "./styles.css";const arrayName = ['Tom','Alice','Matt','Chris'];export default function App() {&nbsp; const [name, setName] = useState();&nbsp;&nbsp;&nbsp; const nameChange = useCallback(() => {&nbsp; &nbsp; const rand = Math.floor(Math.random()*arrayName.length);&nbsp; &nbsp; setName(arrayName[rand])&nbsp; &nbsp;&nbsp; }, []);&nbsp; useEffect(() => {&nbsp; &nbsp; const interval = setInterval(() => {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; setName('');&nbsp; &nbsp; &nbsp; nameChange();&nbsp; &nbsp; }, 2000)&nbsp; &nbsp; return () => clearInterval(interval)&nbsp; }, [nameChange]);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <h1>Hello {name}</h1>&nbsp; &nbsp; </div>&nbsp; );}

茅侃侃

问题是你从不这样做clearInterval。每当组件调用时render,都会发出一个新的间隔。Wrap setIntervalin useEffect,它在组件呈现时被调用。的返回useEffect是一个函数,它指示组件卸载阶段发生的事情。在这里查看更多useEffect(){&nbsp; &nbsp; const tmp = setInterval(()=>{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; setName('');&nbsp; &nbsp; &nbsp; &nbsp; nameChange();&nbsp; &nbsp; &nbsp; &nbsp; console.log(name);&nbsp; &nbsp; }, 2000)&nbsp; &nbsp; return () => { clearInterval(tmp); };}

缥缈止盈

问题是每次渲染您的组件时,您都会创建一个新的间隔。解决办法是把setInterval的调用包装在useEffect中,然后返回一个函数给useEffect清除interval。import React, { useState, useCallback, useEffect } from 'react';import './styles.css';const arrayName = ['Tom', 'Alice', 'Matt', 'Chris'];export default function App() {&nbsp; const [name, setName] = useState();&nbsp; const nameChange = useCallback(() => {&nbsp; &nbsp; const rand = Math.floor(Math.random() * arrayName.length);&nbsp; &nbsp; setName(arrayName[rand]);&nbsp; }, [setName]);&nbsp; useEffect(() => {&nbsp; &nbsp; const intervalId = setInterval(() => {&nbsp; &nbsp; &nbsp; setName('');&nbsp; &nbsp; &nbsp; nameChange();&nbsp; &nbsp; }, 2000);&nbsp; &nbsp; return () => clearInterval(intervalId);&nbsp; }, [nameChange]);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <h1>Hello {name}</h1>&nbsp; &nbsp; </div>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript