简体   繁体   English

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

[英]Error while passing params in axios with React

I'm trying a GET request with Axios by passing certain params as follows,我正在通过如下传递某些参数来尝试使用 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 is fetched from another object passed via contextAPI to this component. customerData是从通过 contextAPI 传递给该组件的另一个对象中获取的。

 const [options, setOptions] = useContext(CustomerContext);

And then it is mapped as follows,然后它被映射如下,

const hostNames = [];
  options.map((name, index) => {
    hostNames.push(name.customer.customHostName);
  });
  const customerData = hostNames[0];

The request is failed with 404 since the customerData is not getting passed as a parameter into the payload.请求因404失败,因为customerData没有作为参数传递到负载中。 So when i checked the log url is like this,所以当我检查日志网址是这样的,

htts://abc.com/v1/route/getAllRoutes?type=mock 404

I tried to log the value of customerData then in that case I can see the expected value to be passed.我尝试记录customerData的值,然后在这种情况下我可以看到要传递的预期值。 Any idea on how to pass the customHostName as param into the payload?关于如何将customHostName作为参数传递到有效负载中的任何想法?

Updated the questions with component I'm referring to,用我所指的组件更新了问题,


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;


You are using a options variable get from the context and If this variable is get from the async function, you need to listen changes on this variable by adding this variable into the useEffect dependency array.您正在使用从上下文中获取的options变量,如果此变量是从异步函数中获取的,则需要通过将此变量添加到 useEffect 依赖项数组中来侦听此变量的更改。

Your version did not work because you were calling fetchData function only one time (after the initial render).您的版本不起作用,因为您只调用了一次 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM