React中如何将useEffect实现的加载屏改写为类组件版本
问题原因
你的代码核心错误是类组件中state的读取方式有误,componentDidMount替换空依赖useEffect的写法本身是完全正确的,两者都是组件首次挂载完成后仅执行一次,符合你延迟关闭加载屏的需求。
具体错误点如下:
- state取值错误:类组件中所有存储在state对象中的属性,必须通过
this.state.属性名的方式读取,你在render方法中直接写this.sourceLoading,读取的是组件实例上不存在的属性,值为undefined,三元表达式始终走false分支,所以加载屏永远不会显示。 - 冗余的绑定逻辑:
componentDidMount是React类组件内置的生命周期方法,React调用时会自动将this绑定到当前组件实例,不需要手动写this.componentDidMount = this.componentDidMount.bind(this),这行属于冗余代码可直接删除。
修正后的完整代码
import React, { Component } from 'react'; class YourComponent extends Component { constructor(props) { super(props); this.state = { sourceLoading: true, }; } componentDidMount() { setTimeout(() => { this.setState({ sourceLoading: false }); }, 1000); } render() { return ( <div> {this.state.sourceLoading ? (<LoadingScreen />) : ( <> {/* 你的页面内容 */} </> )} </div> ); } } export default YourComponent;
内容的提问来源于stack exchange,提问作者kxg
相关产品推荐
相关产品推荐

