[英]Concurrent requests with axios
在React应用程序中,我需要发布表单中的数据。 该帖子将创建一个新的仪表板对象。 完成后,我需要立即更新组件中的选择下拉列表,以包括新添加的仪表板名称。 axios文档说应该这样做:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
这就是我所做的:
class DashboardForm extends Component {
saveDashboard() {
var siteId = this.state.siteId;
var self= this;
return axios.post('/path/to/save/dashboard' + siteId + '/dashboards', {
slug: this.refs.dashboardUrl.value,
name: this.refs.dashboardName.value,
}).then(function (response) {
self.setState({
dashboardId: response.data.dashboardId,
dashboardName: response.data.dashboardName,
submitMessage: (<p>Successfully Created</p>)
});
self.setUrl(siteId, response.data.dashboardId);
}).catch(function (error) {
console.log(error);
self.setState({
submitMessage: (<p>Failed</p>)
});
});
}
getAllDashboards(){
var self = this;
self.setState({siteId: this.props.selectedSiteID});
var getDashboardsPath = "path/to/get/dashboards/" + self.props.selectedSiteID + "/dashboards";
axios(getDashboardsPath, {
credentials: 'include',
method: 'GET',
cache: 'no-cache'
}).then(function (response) {
return response.data.dashboards;
}).then(function (arrDashboards) { //populate options for the select
var options = [];
for (var i = 0; i < arrDashboards.length; i++) {
var option = arrDashboards[i];
options.push(
(<option className="dashboardOptions" key={option.dashboardId} value={option.slug}>{option.name}</option>)
);
}
self.setState({
options: options
});
});
}
saveAndRepopulate() {
axios.all([saveDashboard(), getAllDashboards()])
.then(axios.spread(function (savedDashboard, listOfDashboards) {
// Both requests are now complete
}));
}
}
提交表单时将调用saveAndRepopulate。
问题是我得到以下错误:
error 'saveDashboard' is not defined no-undef
error 'getAllDashboards' is not defined no-undef
我试着做
function saveDashboard() {
但后来我明白了
语法错误:预期的令牌异常((175:13)
|
| function saveDashboard() {
| ^
如何调用这两个函数? 另外,我是否需要将诺言(.then)从单个调用更改为saveAndPopulate?
非常感谢您的指导。
首先,正如@Jaromanda X指出的那样,您应该使用this
调用内部组件函数,并且需要将这些函数绑定到this
。 有多种方法可以执行此操作,其中一种方法是将其绑定到组件构造函数中,例如:
this.saveDashboard = this.saveDashboard.bind(this)
另一件事是在saveDashboard()
和getAllDashboards()
内部返回axios调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.