簡體   English   中英

問題處理 promise 在 useState React

[英]problem handling promise in useState React

從列表中選擇兩個值后,我必須調用一個 api,它返回一個 Json 和信息

通過這種方式,我調用 api 響應 JSON

export default class ProductsService {
   
   async getProducts(channel, category){
       const aux = await axios.post('https://appshop.dapducasse.cl/ducasse-api/api/Qrs?channel='+encodeURIComponent(channel)+'&category='+encodeURIComponent(category)).then(data =>data.data).catch(e => [])
      
       return aux
   } 
}

通過這種方式,我從反應組件進行調用

  const chanelService = new ChanelService();
   const categoryService = new CategoryService();
   const productsService = new ProductsService();

   

   useEffect(() => {
       chanelService.getChanels().then(data => setChanels(data))
       categoryService.getCategories().then(data => setCateries(data))
   }, []);

   const testChargue = async ( ) =>{
       console.log(selectedChannel)
       console.log(selectedCategory)
       const a = await productsService.getProducts(selectedChannel, selectedCategory).then(data => setProducts(data));
       console.log(products)

   }


當我按下按鈕時,function 應該在使用 Channel 和所選產品進行調用的地方執行。

我在第一次單擊按鈕時沒有得到 json,但在第二次單擊時,我認為這是因為執行在 setProducts 定義產品的 state 之前結束。

我假設productssetProducts是指您組件中的本地 state?

在這種情況下,最后一行中的products將始終是處理程序 function 中的“舊”值,因為setProducts不會更新該變量。 該變量僅在重新渲染組件時才會更改,但不會在您的處理程序 function 執行期間更改。 我認為這就是為什么您在按下按鈕兩次時會看到該值的原因。 在第二次單擊時,組件已重新渲染,因此處理程序 function 中的值也已更新。

更多關於反應文檔中“陳舊”state 的信息: https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function

暫無
暫無

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

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