【发布时间】:2021-02-19 10:04:48
【问题描述】:
我刚开始反应……
此代码仅在 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;
【问题讨论】:
标签: javascript reactjs react-hooks react-state react-lifecycle