Javascript 使用React在axios中传递参数时出错
我正在尝试使用Axios通过传递某些参数来获取请求,如下所示Javascript 使用React在axios中传递参数时出错,javascript,reactjs,Javascript,Reactjs,我正在尝试使用Axios通过传递某些参数来获取请求,如下所示 const fetchData=async()=>{ 常数响应=等待axios .get(config.App_URL.getAllMock{ 参数:{ customHostName:customerData, 键入:“模拟”, }, }) .catch((错误)=>{ 错误(`error in fetching the data${error}`); }); let list=[response.data.routeManager]
const fetchData=async()=>{
常数响应=等待axios
.get(config.App_URL.getAllMock{
参数:{
customHostName:customerData,
键入:“模拟”,
},
})
.catch((错误)=>{
错误(`error in fetching the data${error}`);
});
let list=[response.data.routeManager];
setData(列表);
设置加载(真);
};
customerData
是从另一个通过contextAPI传递到此组件的对象获取的
const[options,setOptions]=useContext(CustomerContext);
然后它被映射如下
const主机名=[];
options.map((名称、索引)=>{
hostNames.push(name.customer.customHostName);
});
const customerData=主机名[0];
请求因404
而失败,因为customerData
未作为参数传递到有效负载中。
所以当我检查日志url时是这样的
htts://abc.com/v1/route/getAllRoutes?type=mock 404
我尝试记录customerData
的值,然后在这种情况下,我可以看到要传递的预期值。
您知道如何将customHostName
作为param传递到有效负载中吗
用我提到的组件更新了问题
常量MainContent=()=>{
const[options,setOptions]=useContext(CustomerContext);
const主机名=[];
options.map((名称、索引)=>{
hostNames.push(name.customer.customHostName);
});
const customerData=主机名[0];
//得到所有的嘲笑
const fetchData=async()=>{
常数响应=等待axios
.get(config.App_URL.getAllMock{
参数:{
customHostName:customerData,
键入:“模拟”,
},
})
.catch((错误)=>{
错误(`error in fetching the data${error}`);
});
....
....
....
};
useffect(()=>{
fetchData();
}, []);
返回(
....
....
....
);
};
导出默认主内容;
您正在使用从上下文获取的选项
变量,如果此变量是从异步函数获取的,则需要通过将此变量添加到useEffect依赖项数组中来侦听此变量的更改
您的版本不起作用,因为您只调用了一次fetchData函数(在初始渲染之后)
您正在使用从上下文获取的
options
变量,如果此变量是从异步函数获取的,则需要通过将此变量添加到useEffect依赖项数组中来侦听此变量的更改
您的版本不起作用,因为您只调用了一次fetchData函数(在初始渲染之后)
客户数据来自哪里?404未找到错误。意味着你的url控制台应该有问题,记录你的url,看看会发生什么up@ShubhamVerma:我正在从get请求中获取
customerData
。我尝试记录customerData
,看到了预期值。我将值作为道具传递,在这两种情况下,我都会在尝试控制台日志时看到输出。@TouseefAhmad:是的,问题在于URL,因为只有type
被传递到URL中。我在登录控制台时获取URL。从哪里来customerData
?找不到404错误。意味着你的url控制台应该有问题,记录你的url,看看会发生什么up@ShubhamVerma:我正在从get请求中获取customerData
。我尝试记录customerData
,看到了预期值。我将值作为道具传递,在这两种情况下,我都会在尝试控制台日志时看到输出。@TouseefAhmad:是的,问题在于URL,因为只有type
被传递到URL中。我在登录控制台时得到了URL。如果选项真的如您所期望的那样出现,上次编辑的版本应该可以工作是的,这对我有效。你能更新答案并给出一个简短的解释吗?如果选项真的如你所期望的那样出现,上次编辑的版本应该可以用。是的,这对我有效。请你更新一下答案,并简要解释一下,好吗?
const fetchData = (customerData) => {
...
}
useEffect(() => {
if(options) {
const hostNames = [];
options.map((name, index) => {
hostNames.push(name.customer.customHostName);
});
const customerData = hostNames[0];
fetchData(customerData);
}
}, [options]);