如何避免使用 ref 来渲染加载程序

How can I avoid use ref to render loader

我想在从服务器获取数据时呈现加载器微调器。我已经做到了,但我知道这不是最好的方法,因为使用 "ref"。在这种情况下如何避免使用 "ref" 。我也想在其他组件中渲染微调器。在搜索组件中,我输入了提交按钮以将 inputValue 传递给 App.js

中的 getQuery funn
import React, { Component } from "react";
import Search from "./components/Search";
import RecipesList from "./components/RecipesList";
import Recipe from "./components/Recipe";
import Constansts from "./components/constants";
import axios from "axios";
class App extends Component {
  state = {
    recipesList: [],
    isLoading: false,
    itemId: "",
    recipe: "",
    ingredients: ""
  };

  getQuery = async query => {
    const { key } = Constansts;
    const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`;

    if (query) {
      console.log();
      this.renderLoader();
      try {
        var res = await axios(URL);
        this.setState({
          recipesList: res.data.recipes,
          isLoading: true
        });
        console.log(this.state.isLoading);
        if (this.state.recipesList.length) {
          this.setState({
            isLoading: false
          });
          console.log(this.state.isLoading);
          this.removeLoader();
        }
      } catch (error) {
        console.log(error);
      }
    }
  };
  renderLoader() {
    const recipesRef = this.refs.recipesRef;
    const mark = `<div class="loader">
                    <svg viewBox="0 0 20 20">
                        <path d="M19.315 10h-2.372v-0.205c-0.108-4.434-3.724-7.996-8.169-7.996-4.515 0-8.174 3.672-8.174 8.201s3.659 8.199 8.174 8.199c1.898 0 3.645-0.65 5.033-1.738l-1.406-1.504c-1.016 0.748-2.27 1.193-3.627 1.193-3.386 0-6.131-2.754-6.131-6.15s2.745-6.15 6.131-6.15c3.317 0 6.018 2.643 6.125 5.945v0.205h-2.672l3.494 3.894 3.594-3.894z"></path>
                    </svg>
                  </div>`;
    recipesRef.insertAdjacentHTML("afterbegin", mark);
  }
  removeLoader() {
    const recipesRef = this.refs.recipesRef;
    recipesRef.removeChild(recipesRef.childNodes[0]);
  }

  render() {
    const { isLoading, recipesList, ingredients, recipe } = this.state;

    return (
      <div className="App">
        <div className="wrapper">
          <Search query={this.getQuery} />
          <div className="recipesWrapper" ref="recipesRef">
            <RecipesList isLoading={isLoading} recipesList={recipesList} />
          </div>
        </div>
      </div>
    );
  }
}

export default App;

看起来像反应反模式。

React(视图)应该是数据(state/props)驱动的。一般来说,你不应该 'render' (操纵真正的 DOM)事件处理程序中的任何东西。 Handlers/closures 应该导致状态突变 (setState) 强制做出反应以重新呈现组件视图。最简单的反例说明!

var res = await axios(URL); this.setState({ recipesList: res.data.recipes, isLoading: true });

isLoading 应该在 axios 调用之前设置 - 以便有机会 <Loading/> 渲染。

您可以使用三元运算符简单地呈现加载而不是列表:

{ isLoading ? 
   <Loading />
   : <RecipesList recipesList={recipesList} />
}

阅读整个文档,更完整的教程 - 不是最低要求的片段!真的,了解什么是可能的以及如何去做是完全值得的。