为了账号安全,请及时绑定邮箱和手机立即绑定

使用 React 在 axios 中传递参数时出错

使用 React 在 axios 中传递参数时出错

炎炎设计 2023-02-17 17:32:13
我正在尝试通过如下传递某些参数来使用 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]);


查看完整回答
反对 回复 2023-02-17
  • 1 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号