我正在尝试通过如下传递某些参数来使用 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]);
添加回答
举报
0/150
提交
取消