reactjs - 无法访问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')
);
}
解决方案
您应该使用 npm (yarn) 安装 axios 并将其导入您的 js 文件中:
npm install --save axios
从'axios'导入axios
然后你可以在里面使用带有 axios 的函数 componentDidMount 来发出请求。另外,不要绑定 axios,直接导入即可。
推荐阅读
- azure - Azure 流分析作业 - 固定 1 小时窗口内的累计金额
- ios - 有什么方法可以避免 SwiftUI GeometryReader 阻止嵌套视图在列表中增长?
- java - 寻求有关编译器生成的 lambda 的文档,以将 Java 8 中的专用转换为通用功能对象
- html - 如何使下拉菜单向下打开而不是侧向打开?
- ios13 - 为什么 PKDrawing() != PKDrawing()?(铅笔盒)
- swift - Swift - 更改常量不会显示错误
- arrays - 如何从存储在 mongodb 的嵌套文档中的数组中获取特定项目?
- twig - 当设备在移动设备中时如何使用twig下载pdf文件?
- java - Hibernate INNER JOIN 多对一
- python - 使用列表 A 中的索引替换列表 B 中的索引处的字符串