简体   繁体   English

如何使用 SetInterval 在函数中更改此状态变量?

[英]How to use SetInterval to change this State variable in a function?

I've got this function that takes in a data set (JSON) and returns an object.我有这个函数,它接受一个数据集 (JSON) 并返回一个对象。 But I want to be able to change this data set every 2 seconds.但我希望能够每 2 秒更改一次此数据集。 So I need to somehow change that argument every 2 seconds and then call it so a different object is rendered every two seconds所以我需要以某种方式每 2 秒更改一次该参数,然后调用它,以便每两秒呈现一个不同的对象

The Function:功能:

 const [dataset, setDataSet] = useState(season19) const stats = [{"stat" :"points" , ppg: ""}, {"stat": "rebounds", ast: ""}, {"stat": "assists", reb: ""}] const sortedData = (dataset, nums) => { const finalData = nums.map((stat) => { if(Object.values(stat).includes("points")){ return{ ...stat, ppg: dataset[0].pts } } else if(Object.values(stat).includes("rebounds")){ return{ ...stat, reb:dataset[0].reb } } else if(Object.values(stat).includes("assists")){ return{ ...stat, ast:dataset[0].ast } } }) return finalData }

and im calling it like so:我这样称呼它:

sortedData(dataset,stats)

The other two data sets are season20 and season21另外两个数据集是 season20 和 season21

How would I approach this?我将如何处理这个问题?

What I tried我试过的

I put this into the sortedData function ,我把它放到 sortedData 函数中,

 setInterval(() => {
        setDataset(season20)
      }, 2000)

it works but obviously it only changes to season20, how can I do it so it changes to season21 also它有效,但显然它只更改为第 20 季,我该怎么做才能更改为第 21 季

You need use useEffect and put inside setInterval for every 2s state should be change.你需要使用 useEffect 并把 setInterval 放在每 2s 状态应该改变。 Component should be look about that.组件应该看看。 live code 实时代码

import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
 const [season, setSeason] = useState("season19");

 useEffect(() => {
  const next = setInterval(() => {
    let num = Number(season.substring(6, 9));
    let str = `season${++num}`;

    if (num > 25) return clearInterval(next); // remove setInterval after N-times 

    setSeason(str);
  }, 2000);

    return () => clearInterval(next); // remove setInterval after comp unmounted 

 }, [season]);

 return (
   <div className="App">
     <h1>Hello CodeSandbox</h1>
     <h2>{season}</h2>
   </div>
 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM