【问题标题】:How to delay componentDidMount API fetching in React?如何延迟 React 中的 componentDidMount API 获取?
【发布时间】:2018-05-16 15:06:51
【问题描述】:

我正在使用 Axios 获取数据,并希望延长加载动画(出于个人原因)。

  componentDidMount(){
    var that = this;
    axios.get('api.something.io.json', {
        params: data
      })
      .then(function (response) {
        console.log(response);
        that.setState({
          axiosResponse: response.data,
          isLoading: false
        })
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  ...
  render() {
    if(this.state.isLoading){
      return <div>Waiting...</div>
    }

    return (
      <div className="App">
        <h1>{this.state.axiosResponse.awesomeTitle}</h1>
      </div>
    );

现在Waiting... 会在主组件渲染之前出现一瞬间。我想将"Waiting..." 延长一点,大约 2-3 秒。我尝试在componentDidMount 上使用setTimeout,但它似乎不起作用。

componentDidMount(){
  setTimeout(this.setState({isLoading: 1}), 3000);
  //do axios call here
}

我还尝试在 .then 调用中存根 setTimeout:

  componentDidMount(){
    var that = this;
    axios.get('https://api.rss2json.com/v1/api.json', {
        params: data
      })
      .then(function (response) {
        console.log(response);
        setTimeout(
          that.setState({
            axiosResponse: response.data,
            isLoading: false
          })
          , 3000);

      })
  ...

没有工作。如何将isLoading延长3秒?

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    setTimeout 接受函数作为第一个参数:

        setTimeout(function() {
          that.setState({
            axiosResponse: response.data,
            isLoading: false
          })
         }, 3000); 
    

    而不是:

         setTimeout(
              that.setState({
                axiosResponse: response.data,
                isLoading: false
              }), 3000); 
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2020-05-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多