簡體   English   中英

state 在 api 調用之前未更新

[英]state not being updated before api call

我正在建立一個市場,用戶可以在其中添加自己的產品。 我有一個表單組件,用戶可以在其中輸入有關其產品的詳細信息。 我有一個類別和子類別字段。 一旦用戶選擇了一個類別,子類別表單就會更新(通過使用新類別撥打 api 電話)與該類別相關的子類別列表。 問題是 api 調用是使用最舊的類別而不是新類別進行的。

這是我的代碼

// let's say the initial category is man 
  const [category, setCategory] = useState("men");

  const changeSelectedCategory = (category) => {
    // let's say the user get to choose women category from the picker component listed 
       below

    setCategory(category);
    // the new category is women
  };

  useEffect(() => {

    // making the api call
     getSubCategoriesApi.request({ category: category });
    // logging the api fetched data. i'm sending back the selected category by the user
    // the problem is here. it keeps logging 'men', yet the new category is women
      console.log(getSubCategoriesApi.data());
     
     console.log(category);
    // this logs correctly the new category, which is women. the state has been 
      successfully updated, yet in my api call it wasn't. 
  }, [category]);

<Picker
    items={categories}
    changeSelectedCategory={changeSelectedCategory}
    placeholder="Categorie"
/>

我的快遞代碼。 請注意,我只是發回用戶選擇的類別,以查看它是否已正確更新。

router.post("/products/getSubCategories", async (req, res) => {
  try {
    res.send(req.body);
    // sends old category, men. Yet the user did choose women and 
       state was updated
  } catch (err) {
    res.status(400).send(err);
  }
});

它看起來不像正在調用 changeSelectedCategory 除非您在無法看到的 Picker 組件內調用它。

等待數據時應使用 promise。

getSubCategoriesApi.request({ category: category })
.then(response => {
    console.log(getSubCategoriesApi.data());
  }).catch(error => {
    console.error(error);
  });  

我以某種方式通過使用 axios 作為 api 客戶端而不是以前使用的 apisauce 使其工作。

我的 api 醬鈎

import { useState } from "react";

export default useApi = (apiFunc) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async (...args) => {
    setLoading(true);
    const response = await apiFunc(...args);
    setLoading(false);

    if (!response.ok) return setError(true);

    setError(false);
    setData(response.data);
  };

  return { data, error, loading, request };
};

我的api電話

import { create } from "apisauce";

const apiClient = create({
  baseURL: "http://192.168.1.42:5000/",
});

const endpoint = "/products";

const getSubCategories = (category) =>
  client.post(`${endpoint}/getSubCategories`, category);

export default {
  getSubCategories,
};
```
Form component ( previous one that didn't work )
```
const getProductsCategoriesApi = useApi(listingsApi.getCategories)
const [category, setCategory] = useState("men");

  const changeSelectedCategory = (category) => {
    // let's say the user get to choose women category from the picker component listed 
       below

    setCategory(category);
    // the new category is women
  };

  const getProductsSubCategoriesApi = useApi(listingsApi.getSubCategories);

  useEffect(() => {

    // making the api call
     getSubCategoriesApi.request({ category: category });
    // logging the api fetched data. i'm sending back the selected category by the user
    // the problem is here. it keeps logging 'men', yet the new category is women
      console.log(getSubCategoriesApi.data());
     
     console.log(category);
    // this logs correctly the new category, which is women. the state has been 
      successfully 
}, [categorySelected]);

使用 axios 並放棄我創建的 api 掛鈎的新 api 調用確實有效

useEffect(() => {
    axios
      .post("http://localhost:5000/products/test", { name: categorySelected })
      .then(function (response) {
        // successfully logs the new category. 
        console.log(response.data);

      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  }, [categorySelected]);

暫無
暫無

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

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