想要在几秒钟内显示不同的文本和数组



我有这样一个问题:

我有一个数据数组,还有一个时间数组。这些是阵列:

const Reps = {
TimeOfMove: [1, 2.5, 3, 3.5, 4.5, 5, 6, 10, 12, 13, 14, 15.5],
ScoreOfMove: [60, 85, 42, 60, 70, 80, 90, 100, 90, 40, 0, 20],
};

一秒钟后我想显示数字60,2.5秒后显示数字85,所以这些。。。

此外,我想在一秒钟后将ScoreOfMove数组显示为:[60,0... 0],在2.5秒钟后将数组显示为"[60,85,0...0]"。

这是我到目前为止一直在尝试做的代码,但它对我来说不起作用


import React, { useEffect, useState } from 'react';
import "./styles.css";
const Reps = {
TimeOfMove: [1, 2.5, 3, 3.5, 4.5, 5, 6, 10, 12, 13, 14, 15.5],
ScoreOfMove: [60, 85, 42, 60, 70, 80, 90, 100, 90, 40, 0, 20],
};
let i = 0;
export default function App() {
const [time, setTime] = useState('');
const [timeArr, setTimeArr] = useState([]);
useEffect(() => {
setTimeout(() => {
setTime(Reps.ScoreOfMove[i])
i++;
}, Reps.TimeOfMove[i] * 1000)
}, [time])

return (
<div className="App">
{time}
{timeArr}
</div>
);
}

我希望每次都显示不同的文本,每次都根据它出现的时间显示不同的数组。

setTimeout在指定的超时间隔后仅执行一次。所以您的代码只运行一次。例如,最好将逻辑移到不同的(递归(函数中,这样就可以为Reps.TimeOfMove数组中的每个项调用setTimeout

const setNextTime = i => {
if (i >= Reps.TimeOfMove.length) {
return;    // We're at the end so don't do anything
}
setTimeout(() => {
setTime(Reps.ScoreOfMove[i]);
setNextTime(i++);
}, Reps.TimeOfMove[i] * 1000);
}
useEffect(() => {
setNextTime(0);
}, []);

Matt是对的,所以试试这个:

const Reps = {
TimeOfMove: [1, 2.5, 3, 3.5, 4.5, 5, 6, 10, 12, 13, 14, 15.5],
ScoreOfMove: [60, 85, 42, 60, 70, 80, 90, 100, 90, 40, 0, 20],
};
function App() {
const [time, setTime] = React.useState();
// Create a new array reference with the same length as ScoreOfMove filled with zeros
const timeArr = React.useRef(new Array(Reps.ScoreOfMove.length).fill(0));
React.useEffect(() => {
let timer;
let i = 0;

const tick = () => {
// Keeps a reference of current index
// to be used inside setTimeout, and
// increase real index reference by one for next tick validation
const currentIndex = i++;
timer = setTimeout(() => {
// Update array index with corresponding value
// Run this before setTime to keep things in sync
timeArr.current[currentIndex] = Reps.ScoreOfMove[currentIndex];
setTime(Reps.ScoreOfMove[currentIndex]);

if (Reps.TimeOfMove[i]) { // if there is a next tick
tick();
}
}, Reps.TimeOfMove[currentIndex] * 1000);
}

tick();

return () => clearTimeout(timer); // Clear time out to prevent memory leak
// No dependencies, to execute the effect one single time
}, [])

return (
<div className="App">
<p>{time}</p>
<p>{timeArr.current.toString()}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

最新更新