[英]How to repeat a function in react
I need a repeating function in react.我需要一个重复的 function 反应。 I have an array of words and an element which I want to change every 2 seconds to the following item of the array and again and again.
我有一个单词数组和一个元素,我想每 2 秒将其更改为数组的下一项,并一次又一次地更改。 If the array ends, start over.
如果数组结束,重新开始。 I tried this code:
我试过这段代码:
const words = ['Hi', 'Gutten Tag', 'Hola', 'Bonjour']
const [word, updateWord] = useState(0) // The word would be accessible at words[word]
function handleLoop() {
if (word === words.length - 1) {
updateWord(0)
}
else {
updateWord(word + 1)
}
setTimeout(handleLoop(), 2000)
}
But react thinks that it will cause an infinite loop.但是react认为会导致死循环。
How should I fix it?我应该如何解决它?
You can have the useEffect
hook triggered after every 2 seconds by updating the word
and specifying it in the dependency list.您可以通过更新
word
并在依赖项列表中指定它,每 2 秒触发一次useEffect
挂钩。
const { useEffect, useState } = React; // keep words in a separate constants.js file // if it's a constant and not consumed from an API const words = ["Hi", "Gutten Tag", "Hola", "Bonjour"]; const App = () => { // maintain word as a local state const [word, updateWord] = useState(0); // hook will be triggerd every time word // gets updated after every 2000ms useEffect(() => { let nextWord; // logic stays the same if (word === words.length - 1) { nextWord = 0; } else { nextWord = word + 1; } // update the word setTimeout(() => updateWord(nextWord), 2000); }, [word]); return ( <p>{words[word]}</p> ); } ReactDOM.render(<App />,document.getElementById('react'));
<div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
Fix:使固定:
const words = ['Hi', 'Gutten Tag', 'Hola', 'Bonjour']
const [word, updateWord] = useState(0) // The word would be accessible at words[word]
function handleLoop() {
if (word === words.length - 1) {
updateWord(0)
}
else {
updateWord(word + 1)
}
}
setInterval(handleLoop, 2000)
I think setInterval is better way, here我认为 setInterval 是更好的方法,在这里
const words = ['Hi', 'Gutten Tag', 'Hola', 'Bonjour']
const [word, updateWord] = useState(0) // The word would be accessible at words[word]
let handleLoop = function() {
if (word === words.length) {
updateWord(0)
}
else {
updateWord(word + 1)
}
console.log(words[word])
}
setInterval(handleLoop, 2000)
function countDown(fromNumber) {
console.log(fromNumber);
let nextNumber = fromNumber - 1;
if (nextNumber > 0) {
countDown(nextNumber);
}
}
countDown(3);
function countDown(fromNumber) { console.log(fromNumber); let nextNumber = fromNumber - 1; if (nextNumber > 0) { countDown(nextNumber); } } countDown(3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.