首页 > 解决方案 > 无法访问axios

问题描述

我正在尝试从反应组件访问 axios 调用。

我试图通过资源传递 axios 并通过 this.axios 访问它但错误:this.axios.post 不是函数

问题:如何在我的 react 组件中导入 axios.js。是否可以从其他 javascript 文件访问 axios.js。我在这里没有使用任何 webpack。

.aspx

<%@ Page Language="C#" MasterPageFile="~/ParentPage" AutoEventWireup="true" CodeBehind="Session.aspx.cs" Inherits="SessionPage" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolderMiddlePanel" runat="Server">

    <script type="text/javascript">
    let socketID = '<%=Session["userSocketID"] %>';
    let identityUserName = '<%= HttpContext.Current.User.Identity.Name.Replace(@"\", @"\\") %>';
    </script>

    <!--React Script-->
    <script src="Scripts/axios.js"></script>
    <script src="Scripts/react.js"></script>
    <script src="Scripts/react-dom.js"></script>

  <div class="Session">
      <div id="Session_React"></div>
  </div>
  <script  type="text/javascript" src="includes/scripts/Session.js"></script>
  <script>
    let res = {
      makePing: makePing,
      axios: axios,
     };
    renderSharing(res);
  </script>
</asp:Content>

会话.js

type Props = {
  resources: any;
}

type state = {
  activeSessions : any;
  CurrentUserName: any;
}   

class SessionSharing extends React.Component<Props, state> {

  private makePing: any;
  private axios: any;

  constructor(props) {
    super(props);

    this.makePing = res.makePing.bind(this);
    this.axios = res.axios.bind(this);

    this.state = {
      activeSessions: []
    };
  }

  getSession() {
    var path = "Session.aspx/GetSessions";
    this.axios
      .post(path, { withCredentials: true })
      .then(response => {
        let element = JSON.parse(response.data.d);

        this.setState({
          activeSessions: element
        });
      })
      .catch(error => {
        console.error(error);
      });
  }


  render() {
    return (
      <div>
        {this.renderSessionDetails()}
      </div>
    );
  }
}

function renderSharing(res){
  ReactDOM.render(
  <Session resources={res}/>,
  document.getElementById('Session_React')
);  
}

标签: reactjstypescriptwebformsaxios

解决方案


您应该使用 npm (yarn) 安装 axios 并将其导入您的 js 文件中:

npm install --save axios

从'axios'导入axios

然后你可以在里面使用带有 axios 的函数 componentDidMount 来发出请求。另外,不要绑定 axios,直接导入即可。


推荐阅读