亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 React 在 axios 中傳遞參數時出錯

使用 React 在 axios 中傳遞參數時出錯

炎炎設計 2023-02-17 17:32:13
我正在嘗試通過如下傳遞某些參數來使用 Axios 進行 GET 請求,const fetchData = async () => {    const response = await axios      .get(config.App_URL.getAllMock, {        params: {          customHostName: customerData,          type: "mock",        },      })      .catch((error) => {        console.error(`Error in fetching the data ${error}`);      });    let list = [response.data.routeManager];    setData(list);    setLoading(true);  };customerData從通過 contextAPI 傳遞給此組件的另一個對象中獲取。 const [options, setOptions] = useContext(CustomerContext);然后它被映射如下,const hostNames = [];  options.map((name, index) => {    hostNames.push(name.customer.customHostName);  });  const customerData = hostNames[0];請求失敗,404因為customerData 沒有作為參數傳遞到負載中。所以當我檢查日志 url 是這樣的時,htts://abc.com/v1/route/getAllRoutes?type=mock 404我嘗試記錄 then 的值,customerData在這種情況下我可以看到要傳遞的預期值。關于如何將customHostNameas 參數傳遞到有效載荷中的任何想法?用我指的組件更新了問題,const MainContent = () => {  const [options, setOptions] = useContext(CustomerContext);  const hostNames = [];  options.map((name, index) => {    hostNames.push(name.customer.customHostName);  });  const customerData = hostNames[0];  // Get all the mock  const fetchData = async () => {    const response = await axios      .get(config.App_URL.getAllMock, {        params: {          customHostName: customerData,          type: "mock",        },      })      .catch((error) => {        console.error(`Error in fetching the data ${error}`);      });    ....    ....    ....  };  useEffect(() => {    fetchData();  }, []);  return (    <div>     ....     ....     ....    </div>  );};export default MainContent;
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

您正在使用options從上下文中獲取的變量,如果此變量是從異步函數中獲取的,則需要通過將此變量添加到 useEffect 依賴項數組中來偵聽此變量的更改。


您的版本不起作用,因為您只調用了一次 fetchData 函數(在初始渲染之后)。


  const fetchData = (customerData) => {

    ...

  }  


   useEffect(() => {

      if(options) {

       const hostNames = [];

       options.map((name, index) => {

       hostNames.push(name.customer.customHostName);

       });

        const customerData = hostNames[0];


        fetchData(customerData);

      } 

     }, [options]);


查看完整回答
反對 回復 2023-02-17
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號