[英]Error while passing params in axios with React
我正在通過如下傳遞某些參數來嘗試使用 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
沒有作為參數傳遞到負載中。 所以當我檢查日志網址是這樣的,
htts://abc.com/v1/route/getAllRoutes?type=mock 404
我嘗試記錄customerData
的值,然后在這種情況下我可以看到要傳遞的預期值。 關於如何將customHostName
作為參數傳遞到有效負載中的任何想法?
用我所指的組件更新了問題,
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;
您正在使用從上下文中獲取的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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.