【发布时间】:2021-09-25 07:05:36
【问题描述】:
我对 React 还很陌生。我目前在 React 中使用 useEffect 制作了一个加载屏幕,但我不确定如何使用类组件制作它。这是我的功能组件。
const [sourceLoading, setSourceLoading] = React.useState(true);
// control when to stop loading
useEffect(() => {
setTimeout(() => {
setSourceLoading(false);
}, 1000);
}, [])
return (
<div>
{sourceLoading ? (<LoadingScreen />): (
<>
</>
)}
</div>
);
我目前正在像这样转换函数,但它不起作用,而且我的加载屏幕从未出现。我哪里错了? componentDidMount 在这里不是 useEffect 的正确替代吗?
this.state = {
sourceLoading: true,
};
this.componentDidMount = this.componentDidMount.bind(this);
componentDidMount() {
setTimeout(() => {
this.setState({ sourceLoading: false});
}, 1000);
}
render() {
return (
<div>
{this.sourceLoading ? (<LoadingScreen />) : (<>
</>
)}
</div>
);
}
【问题讨论】:
-
使用这个
{this.state.sourceLoading ? (<LoadingScreen />) : (<> </>)},因为sourceLoading是一个属于this.state的对象。
标签: javascript reactjs use-effect react-class-based-component