React使用axios的坑:每次都要请求两次,而且前后端相同配置

React使用axios的坑:每次都要请求两次,而且前后端相同配置

项目:react-antd-axios

接口会调用两次
接口会调用两次,但是页面中并没有写调用两次的方法,componentDidMount中值调用了一次,反复查看没有问题,axios中封装的api也没有出现问题。

我的项目解决:
在包裹着content的路由页面,也就是主页面中componentDidMount写了方法,但是并没有调用api

  componentDidMount() {
    this.getPath();
  }
  getPath() {
    // 获取当前路径
    const pathname = this.props.location.pathname;
    //获取当前所在的目录层级
    const rank = pathname.split("/");
    //rank = ["","policy-engine","nas-client"]
    console.log(rank);
    switch (rank.length) {
      case 2: //一级目录
        this.setState({
          selectedKeys: [pathname]
        });
        break;
      case 3: //二级目录,要展开一个subMenu
        this.setState({
          selectedKeys: [pathname],
          openKeys: [rank.slice(0, 2).join("/")]
        });
        break;
      case 4: //三级目录,要展开两个subMenu
        this.setState({
          selectedKeys: [pathname],
          openKeys: [rank.slice(0, 2).join("/"), rank.slice(0, 3).join("/")]
        });
        break;
    }
  }

主要是
componentDidMount() {
this.getPath();
}这一部分写了调用函数

解决方法

componentWillMount() {
    this.getPath();
  }

写在componentWillMount就能解决。

注意:这个只是我的项目问题,仅供参考;其他问题看查看

axios调用两次接口

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用React Hooks对Axios进行二次封装的示例代码: ```javascript import { useState, useEffect } from 'react'; import axios from 'axios'; const useAxios = (url, method, body = null, headers = null) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { axios({ method: method, url: url, data: body, headers: headers }) .then(res => { setResponse(res.data); }) .catch(err => { setError(err); }); }, [url, method, body, headers]); return { response, error }; }; export default useAxios; ``` 在这个示例中,我们使用了useState和useEffect两个React Hooks。useState用于在组件中存储状态,而useEffect用于在组件渲染时执行副作用操作。我们将Axios请求封装在useAxios自定义钩子中,并将url,method,body和headers作为参数传递。在useEffect中,我们使用Axios发送请求,并根据响应设置状态。最后,我们返回一个包含响应和错误的对象。 使用示例: ```javascript import useAxios from './useAxios'; const MyComponent = () => { const { response, error } = useAxios('https://jsonplaceholder.typicode.com/posts', 'get'); if (error) return <div>Error: {error.message}</div>; if (!response) return <div>Loading...</div>; return ( <ul> {response.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> ); }; ``` 在这个示例中,我们使用useAxios钩子从https://jsonplaceholder.typicode.com/posts获取帖子列表。我们根据响应渲染帖子列表,如果出现错误,则显示错误消息,如果响应尚未返回,则显示加载消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值