为什么钩子的代码(功能)保持呈现?(与Class相比)



我刚开始反应…

这段代码使用布尔值在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;

每次渲染时调用函数组件。这意味着在状态改变后的每次重新呈现时也会创建超时,就像在第一个示例中实现的那样。要使用组件生命周期,您应该使用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;

因为你在状态中初始化的isLoading值是true。当状态被改变时,功能组件呈现,而这不会发生在基于类的组件中,因为你已经使用了组件生命周期方法。你应该使用"useeffect";在功能组件

useEffect(() => {
setTimeout(() => {
setIsLoading(!isLoading);
}, 3000);
});

你可以在这里阅读https://reactjs.org/docs/hooks-effect.html

MubtadaNaqvi的回答将不幸导致无限循环。你应该正确应用useEffect:

useEffect(() => {
setTimeout(() => {
setIsLoading(isLoading => !isLoading);
}, 1000);
}, [])

最新更新