簡體   English   中英

反應,setInterval 無法正常工作,h1 元素未正確更新

[英]React, setInterval not working properly, h1 element not being updated correctly

我想創建一個簡單的 React 應用程序,它使用 setInterval 函數每秒更新一個 h1 元素。 我有一個帶有字符串的數組,每秒我想從該數組中隨機選擇一個字符串並在 h1 中使用該字符串。 但是我的代碼不能正常工作。 h1 不是每秒更新一次,而是每毫秒更新一次。

import PersonalInfo from './PersonalInfo.js'
import { useState } from 'react';

function App() {
  const myPersonalInfo = ['books', 'music', 'code']; 
  const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);

  setInterval(() => {
    changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
  }, 2000);

  return (
    <div className="App">
      <PersonalInfo title={state} />
    </div>
  );
}

export default App;
function PersonalInfo({ title}) {
    return <div>
        <h1>I Love {title} </h1>
    </div>
}

export default PersonalInfo

    import PersonalInfo from './PersonalInfo.js'
    import { useState } from 'react';
    
    function App() {
      const myPersonalInfo = ['books', 'music', 'code']; 
      const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
    
      useEffect(() => {
         setInterval(() => {
            changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
         }, 2000);
      }, [])
    
      return (
        <div className="App">
          <PersonalInfo title={state} />
        </div>
      );
    }
    
    export default App;

使用 useEffect 掛鈎

使用反應 useEffect

具有空依賴項的 useEffect 僅在第一次渲染時運行

組件卸載的 清除間隔

import PersonalInfo from './PersonalInfo.js'
import React, { useState, useEffect } from 'react';

function App() {
  const myPersonalInfo = ['books', 'music', 'code']; 
  const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);

  useEffect(() => {
    const intervalId = setInterval(() => {
      changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
    }, 2000);
    
    return () => clearInterval(intervalId)
  }, [])

  return (
    <div className="App">
      <PersonalInfo title={state} />
    </div>
  );
}

export default App;

使用 useEffect 並將 state 設置為依賴項。

useEffect(() => {
  setInterval(() => {
    changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
  }, 2000);
}}, [state])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM