炎炎設(shè)計(jì)
2023-02-17 17:32:13
我正在嘗試通過(guò)如下傳遞某些參數(shù)來(lái)使用 Axios 進(jìn)行 GET 請(qǐng)求,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從通過(guò) contextAPI 傳遞給此組件的另一個(gè)對(duì)象中獲取。 const [options, setOptions] = useContext(CustomerContext);然后它被映射如下,const hostNames = []; options.map((name, index) => { hostNames.push(name.customer.customHostName); }); const customerData = hostNames[0];請(qǐng)求失敗,404因?yàn)閏ustomerData 沒(méi)有作為參數(shù)傳遞到負(fù)載中。所以當(dāng)我檢查日志 url 是這樣的時(shí),htts://abc.com/v1/route/getAllRoutes?type=mock 404我嘗試記錄 then 的值,customerData在這種情況下我可以看到要傳遞的預(yù)期值。關(guān)于如何將customHostNameas 參數(shù)傳遞到有效載荷中的任何想法?用我指的組件更新了問(wèn)題,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貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
您正在使用options從上下文中獲取的變量,如果此變量是從異步函數(shù)中獲取的,則需要通過(guò)將此變量添加到 useEffect 依賴項(xiàng)數(shù)組中來(lái)偵聽(tīng)此變量的更改。
您的版本不起作用,因?yàn)槟徽{(diào)用了一次 fetchData 函數(shù)(在初始渲染之后)。
const fetchData = (customerData) => {
...
}
useEffect(() => {
if(options) {
const hostNames = [];
options.map((name, index) => {
hostNames.push(name.customer.customHostName);
});
const customerData = hostNames[0];
fetchData(customerData);
}
}, [options]);
添加回答
舉報(bào)
0/150
提交
取消