显示加载微调器

时间:2019-06-28 00:58:01

标签: reactjs axios

问题

现在我的代码显示了一个微调器,表明我仍在等待API的响应。

我没有考虑到我的回答准确,快速并且使微调框消失了...

图像的实际渲染很慢。

问题

在未渲染图像时如何显示微调器?

代码

主应用程序

std::integer_sequence<int, 7, 15, 28>

用户组件

import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import Users from "./components/Users";
import Navbar from "./components/Navbar";
import "./App.css";
import Upload from "./components/Upload";
import Search from "./components/Search";
import Mix from "./components/Mix";

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

  const searchUsers = text => {
    axios
      .get(
        `https://api.giphy.com/v1/stickers/search?q=${text}&api_key=${
          process.env.REACT_APP_GIPHY_CLIENT_ID
        }`
      )
      /* Trigger re-render. The users data will now be present in 
       component state and accessible for use/rendering */
      .then(res => setUsers(res.data.data))
      // log error
      .catch(error => console.error(error))
      // set loading finished
      .finally(() => setLoading(false));
  };

  return (
    <div className="App">
      <Navbar />
      <Upload />
      <Search searchUsers={searchUsers} />
      <Mix />
      <div className="ui horizontal inverted divider">
        {" "}
        <i aria-hidden="true" className="youtube icon" />
      </div>
      <div container>
        <Users loading={loading} users={users} />
      </div>
    </div>
  );
};

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

export default App;

微调组件

import React from "react";
import UserItem from "./UserItem";
import Spinner from "./Spinner";

const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />;
  } else {
    return (
      <div className="ui relaxed five column grid">
        {users.map(user => (
          <UserItem key={user.id} gif={user.images.original.url} />
        ))}
      </div>
    );
  }
};

export default Users;

用户项目组件

import React from "react";

const Spinner = () => {
  return (
    <div className="ui center aligned fluid container">
      <div className="ui active inline loader" />
    </div>
  );
};

export default Spinner;

1 个答案:

答案 0 :(得分:0)

您可以在img标签上使用onLoad方法(它是React支持的两个image events之一)。图像加载完成后,将调用onLoad函数。

在您的UserItem组件中:

const UserItem = ({ gif }) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  return (
    <div className="column">
      { !imageLoaded && <Spinner />}
      <img alt="" src={gif} className="ui image" onLoad={() => setImageLoaded(true} />
    </div>
  )
};