簡體   English   中英

如何在反應中使用 Axios 和異步/等待語法?

[英]How to use Axios with async/await syntax in react?

我想使用 axios 從我的數據庫中檢索一個數組並將其顯示在反應組件中。 我使用了 componentDidMount() 生命周期方法和異步/等待語法,如下所示:

state = {
      products: []
}

async componentDidMount() {
     const res=  await axios.get(http://santacruz.clickysoft.net/api/public/home-product)
     .then(res => this.setState({products: res.data.products})
     .catch(err => console.log(err));
}

class組件的返回語句如下:

 return (
  <div className="wwd animated" data-animation="bounceInLeft">
    <div className="wwd-slider">
      <div className="container-fluid">
        <div className="row">
          <div className="col-md-12 nlrp">
            <div className="owl-carousel owl-theme">
              {
                this.state.product.map( product => 
                  <div className="item">
                  <img src="images/p-01.png" className="img-fluid" />
                  <div className="wwd-over">
                    <a href="#">{product.product_name}</a>
                      <p>{product.info}</p>
                  </div>
                </div>
                )}
              }
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

當我運行它時,它工作正常,state 已更新,我可以看到其中的所有產品,但似乎是因為每次 state 更新時,組件都會重新呈現自己,而我在 web 頁面上的元素 alignment 完全受到干擾。

我希望請求等到所有元素都從 db 中獲取,然后 map 在 state 上只獲取一次。 有人可以告訴我如何實現這一目標嗎?

當我在 state 中對數組的所有 14 項進行硬編碼時,我可以按如下所示獲得所需的對齊輪播視圖:

在此處輸入圖像描述

但是當我在同一個 map function 中使用 axios 從后端獲取數據時,一切都會受到干擾。

在此處輸入圖像描述

誰能知道為什么會這樣?

因此,對於您給出的示例,如果您仍在使用.then.catch ,則 await (以及對res的分配)是不必要的。 如果你想使用 await,更慣用的方式是這樣的:

async componentDidMount() {
     try {
         const res = await axios.get(http://santacruz.clickysoft.net/api/public/home-product)

         this.setState({products: res.data.products})
     } catch(err) {
         console.log(err)
     }
}

至於為什么它會導致渲染問題,嗯,那是因為貓頭鷹輪播不兼容 React 不做一些工作。 當你初始化 owl carousel 時,它會根據需要更改 DOM,這意味着它需要你的 html 並對其進行相當多的修改 - 如下所示:

<div className="owl-carousel owl-theme">
   <div className="item">
                  …
   </div>
</div>

類似於:

<div class="owl-carousel owl-theme owl-loaded owl-drag">
    <div class="owl-stage-outer"><div class="owl-stage" style="transform: translate3d(-1176px, 0px, 0px); transition: 0s; width: 4704px;">
             <div class="owl-item cloned" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
            <div class="owl-item active" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
            <div class="owl-item cloned" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
        </div></div>
     <div class="owl-nav">…</div>
</div>

但隨后 React 運行更新,查看 DOM,並說“那不對,讓我修復它”,然后將其設置回原來的狀態,這消除了貓頭鷹輪播所做的所有工作。 所以你所有的 div 都只是普通的 div 堆疊在一起,而不是在輪播中。 因此,要解決此問題,我建議使用專為 React 設計的旋轉木馬,或React owl 旋轉木馬 package

你應該使用

axios.get(...).then(...).catch(...)

要么

const result = await axios.get(...)
this.setState({products: result.data.product})

當您使用await關鍵字時,您應該將其視為同步操作,因此您不需要回調。

UPD:好像你有錯字,你應該這樣分配

this.setState({products: result.data.product})

this.state.product s .map 也有錯字

您可以在 componentDidMount 中調用 function 為您調用 api

componentDidMount() { 
  this.callAxiosApi(); 
}

So, in this function call the api through axios using async/await 
if you get response then set the state, if not console the error simple is that
callAxiosApi = async () => {
 try{
    const res = await axios.get("http://santacruz.clickysoft.net/entercode hereapi/public/home-product");
    if(res) this.setState({products: res.data.products})
    }catch(err){
       err => console.log(err)
    }
}

暫無
暫無

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

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