簡體   English   中英

React 條件渲染 - 加載組件

[英]React Conditional Rendering - Loading Component

在導航項之間切換時,我試圖調用我的加載組件。 每次單擊它都會獲取新數據,所以我想在等待數據加載時將我的加載組件放在那里。

我感到困惑的地方是我正在映射數據以顯示我的故事。 在那個 map(下)中,我是否添加三元運算符來呈現 `Loading/> 組件? 這就是我迷路的地方。 我試圖關注這篇文章

import { useState, useEffect } from "react";
import Story from "./Story";
import { useParams } from "react-router-dom";
import Masthead from "./Masthead";
import LoadingBar from "./LoadingBar";

export default function News() {
  const { section } = useParams();
  console.log("Section: ", section);

  const [error, setError] = useState(null);
  const [results, setResults] = useState(null);

  useEffect(() => {
    fetch(
      `https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=4fzCTy6buRI5xtOkZzqo4FfEkzUVAJdr`
    )
      .then((res) => res.json())
      .then((data) => {
        setTimeout(() => setResults(data.results), 1500);
        console.log("Success ", data);
      })
      .catch((error) => {
        console.log("Error", error);
        setError(error);
      });
  }, [section]);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!results) {
    return <LoadingBar type={"cylon"} color={"#193152"} />; // this Loading bar is called when first fetching data, but doesn't re-rending when refetching new data
  } else {
    return (
      <>
        <Masthead />
        <ul className="stories">
          {results.map((story, index) => (        // Do I add the ternary operator here?
            <Story                             
              key={index}
              title={story.title}
              abstract={story.abstract}
              img={story.multimedia[0].url}
              alt={story.multimedia[0].caption}
              link={story.url}
            />
          ))}
        </ul>
      </>
    );
  }
}

我的帶路由器的 App.js

import { BrowserRouter as Router, Route } from "react-router-dom";
import Masthead from "./components/Masthead";
import News from "./components/News";
import Header from "./components/Header";
import "./App.css";

export default function App() {
  return (
    <>
      <Header title={"The React Times"} />
      <Router>
        <Route path="/" exact component={Masthead} />
        <Route path="/news/:section" exact component={News} />
      </Router>
    </>
  );
}

和我的標頭部分,我有我的導航項目

import React from "react";
import { NavLink } from "react-router-dom";

var sections = [
  "arts",
  "business",
  "health",
  "home",
  "movies",
  "opinion",
  "politics",
  "science",
  "sports",
  "technology",
];

export default function Masthead() {
  return (
    <div className="masthead">
      <ul>
        {sections.map((section) => {
          return (
            <li key={section}>
              <NavLink classname="navItem" to={`/news/${section}`}>
                {section}
              </NavLink>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

我認為您的問題是,只要結果不正確,您就會顯示 Loading Bar 組件。 但是,在進行提取之前,您沒有將結果設置為 null,因此它仍會保留上次提取的內容,並且加載欄將永遠不會再次呈現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM