在数据加载之前不要渲染-反应

时间:2019-08-27 13:30:34

标签: reactjs redux

我正在使用react-router进行导航。我希望路线之间的过渡像youtube和facebook一样。我在安装的每个组件中都有API调用。我试图阻止加载下一个URL(组件),直到它获取了数据(如youtube)为止。取而代之的是,我想要的是当前组件仍显示在顶部,并带有一个进度条,直到下一个url(component)完成获取其数据为止。我如何才能做到这一点呢?谢谢

1 个答案:

答案 0 :(得分:0)

您将需要在父组件中进行提取。然后,您可以根据获取状态呈现所需的任何组件。如果提取完成,则渲染NewComponent。如果仍在获取,请呈现CurrentComponent。

import React, { useState } from "react";
import ReactDOM from "react-dom";

const CurrentComponent = () => <div>I am current</div>;
const NewComponent = () => <div>I am new</div>;

const App = () => {
  const [loading, setLoading] = useState(true);

  // this simulates your fetch
  setTimeout(() => {
    setLoading(false);
  }, 2000);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Component:</h2>
      {loading ? <CurrentComponent /> : <NewComponent />}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

或使用React-Router:

进行提取,提取完成后,使用history.push转到新路线。参见this post