【问题标题】:How to write an if statement inside of an API call to resemble a loading state?如何在 API 调用中编写 if 语句以模拟加载状态?
【发布时间】:2020-10-10 21:56:54
【问题描述】:

我从用户输入中获取一个值并将其作为argument 放入API 调用中,以显示与用户输入相关的结果。加载该 API 数据时。为简单起见,我想登录控制台“加载”,当数据加载时,console.log 数据。我不知道如何在我的 axios 调用之间设置 if 语句。

另外,我是否正确使用state?我应该在constructor 中定义query 值和isLoading 吗?

class App extends Component {
  constructor() {
    super();
    this.state = {
      movieList: [],
    }
  }


  // propped value from user input which goes inside the API call as a parameter
  handleSearch = (value) => {

    this.setState({
      query: value,
      isLoading: true
    })

    //if isLoading === true --> console.log('Loading');
    axios({
      url: `apicall${value}2`,
      method: 'GET',
      responseType: 'JSON',
      // isLoading === false --> console.log('movieList');
    }).then((response => {
      let movieList = response;
      
      this.setState({
        movieList,
        isLoading: false,
        query: ''
      })

    }))
  }

【问题讨论】:

  • 为什么要添加 if 语句,您可以在 axios 调用之前将日志添加为“正在加载”,然后在 then() 函数中添加“movieList”。
  • 我猜你还没有在构造函数内部的状态中定义其他变量

标签: javascript reactjs api axios components


【解决方案1】:

在您的代码中,您的状态中没有 queryisLoading。我在下面的代码中更新了它们。

console.log在代码中调用API前后,可以使用setStates回调函数。

我重构了代码以使其看起来干净。

class App extends Component {
  constructor() {
    super();
    this.state = {
      movieList: [],
      query: "",
      isLoading: false
    };
  }

  movieListSearchInitiated = value => {
    this.setState(
      {
        query: value,
        isLoading: true
      },
      () => {
        // Use setStates callback function to log

        console.log("Loading");
      }
    );
  };

  movieListSearchSuccess = movieList => {
    this.setState(
      {
        movieList,
        isLoading: false,
        query: ""
      },
      () => {
        // Use setStates callback function to log

        console.log(this.state.movieList);
      }
    );
  };

  movieListApiCall = value => {
    return axios({
      url: `apicall${value}2`,
      method: "GET",
      responseType: "JSON"
    });
  };

  handleSearch = value => {
    this.movieListSearchInitiated(value);
    this.movieListApiCall(value).then(movieList => {
      this.movieListSearchSuccess(movieList);
    });
  };
}

希望您在处理 API 请求时出错。

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 2021-10-13
    • 2021-10-16
    • 1970-01-01
    • 2010-10-29
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多