我刚开始反应...
此代码仅在3秒后使用布尔值呈现。
但是下面的代码一直在渲染..渲染..正在渲染...几乎每三秒一次。
import React, { useState } from "react";
const App = () => {
const [isLoading, setIsLoading] = useState(true);
setTimeout(() => {
setIsLoading(!isLoading);
}, 3000);
return <h1>{isLoading ? "Loading" : "we are ready"}</h1>;
};
export default App;但这段代码运行良好。原因何在?
import React, { Component } from "react";
class App extends React.Component {
state = {
isLoading: true,
};
componentDidMount() {
setTimeout(() => {
this.setState({
isLoading: false,
});
}, 3000);
}
render() {
return <div>{this.state.isLoading ? "Loading..." : "we are ready"}</div>;
}
}
export default App;发布于 2021-02-19 18:15:52
在每次渲染时都会调用一个函数组件。这意味着超时也是在状态更改后的每次重新呈现时创建的,当像第一个示例一样实现时。要使用组件生命周期,您应该使用useEffect挂钩:https://reactjs.org/docs/hooks-reference.html#useeffect
import React, { useEffect, useState } from "react";
const App = () => {
const [isLoading, setIsLoading] = useState(true);
// Set a timeout ONCE when the component is rendered for the first time
// The second argument [] signifies that nothing will trigger the effect during re-renders
useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 3000);
}, [])
return <h1>{isLoading ? "Loading" : "we are ready"}</h1>;
};
export default App;发布于 2021-02-19 18:14:20
因为您正在使用状态中的true值初始化isLoading。每当状态改变时,功能组件都会重新呈现,而在基于类的组件中不会发生这种情况,因为您已经使用了组件生命周期方法。您应该在功能组件中使用"useEffect“。
useEffect(() => {
setTimeout(() => {
setIsLoading(!isLoading);
}, 3000);
});发布于 2021-02-19 18:16:29
不幸的是,来自MubtadaNaqvi的答案将导致无限循环。您应该正确应用useEffect:
useEffect(() => {
setTimeout(() => {
setIsLoading(isLoading => !isLoading);
}, 1000);
}, [])https://stackoverflow.com/questions/66275467
复制相似问题