[英]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.