【问题标题】:Using useEffect (or the equivalent) for class component (making a loading screen)对类组件使用 useEffect(或等效项)(制作加载屏幕)
【发布时间】: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 ? (&lt;LoadingScreen /&gt;) : (&lt;&gt; &lt;/&gt;)},因为sourceLoading是一个属于this.state的对象。

标签: javascript reactjs use-effect react-class-based-component


【解决方案1】:

你需要像这样访问渲染函数中的状态

{this.state.sourceLoading ? (<LoadingScreen />) : null}

【讨论】:

  • 另外你不必绑定生命周期方法 this.componentDidMount = this.componentDidMount.bind(this);
【解决方案2】:

如果您更改此行,它对我有用:

{this.sourceLoading ? (content) : ""}
// should be
{this.state.sourceLoading ? (content) : ""}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      sourceLoading: true,
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        sourceLoading: false
      });
    }, 1000);
  }

  render() {
    return ( 
      <div>
        {this.state.sourceLoading ? "loading" : "not"}
      </div>
    );
  }
}

ReactDOM.render( <App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2023-04-11
    • 2020-11-14
    相关资源
    最近更新 更多