大家早上好/下午好,
我已经使用 React 几个月了。我试图避免使用 React 组件,而是使用 React Hooks,但我不得不承认有时我的目标会变得复杂。
其中一个时刻是在渲染组件后仅执行一次函数。在我的情况下,我只想在所有组件都被渲染后执行一次递归函数( typeText
)。
下面是一个 react 项目的例子:
import React, { useEffect, useState } from "react";
export default function App() {
const [word, setWord] = useState("");
const list = ["Bag", "Door", "Shelving"];
let isWriting = true;
let selectedWord = 0,
position = 0,
delay = 0;
const typeText = () => {
if (isWriting === true) {
if (position < list[selectedWord].length) {
setWord(word + list[selectedWord].charAt(position++));
delay = 100;
} else {
isWriting = false;
delay = 1500;
}
} else {
if (word.length > 0) {
setWord(word.substring(0, word.length - 1));
delay = 40;
} else {
isWriting = true;
selectedWord = (selectedWord + 1) % list.length;
position = 0;
delay = 300;
}
}
setTimeout(() => typeText(), delay);
};
useEffect(() => {
typeText();
}, []);
return (
<div className="App">
<h1>{word}</h1>
</div>
);
}
非常感谢大家的帮助、问候和拥抱!
最佳答案
您发布的不是 React 代码,您介意发布 React 部分吗?无论如何,在钩子(Hook)中,要在渲染后运行一次,只需使用 useEffect
钩:
const MyComponent = () => {
useEffect(() => {
// your code here
}, []);
return <Whatever you="are rendering" />;
};
关于javascript - 在 React 中渲染后执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66042852/