猿问

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

我正在尝试通过如下传递某些参数来使用 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;


炎炎设计
浏览 172回答 1
1回答

智慧大石

您正在使用options从上下文中获取的变量,如果此变量是从异步函数中获取的,则需要通过将此变量添加到 useEffect 依赖项数组中来侦听此变量的更改。您的版本不起作用,因为您只调用了一次 fetchData 函数(在初始渲染之后)。&nbsp; const fetchData = (customerData) => {&nbsp; &nbsp; ...&nbsp; }&nbsp;&nbsp;&nbsp; &nbsp;useEffect(() => {&nbsp; &nbsp; &nbsp; if(options) {&nbsp; &nbsp; &nbsp; &nbsp;const hostNames = [];&nbsp; &nbsp; &nbsp; &nbsp;options.map((name, index) => {&nbsp; &nbsp; &nbsp; &nbsp;hostNames.push(name.customer.customHostName);&nbsp; &nbsp; &nbsp; &nbsp;});&nbsp; &nbsp; &nbsp; &nbsp; const customerData = hostNames[0];&nbsp; &nbsp; &nbsp; &nbsp; fetchData(customerData);&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp;}, [options]);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答