【发布时间】:2017-03-12 23:09:37
【问题描述】:
在 React 应用程序中,我需要从表单中发布数据。该帖子创建了一个新的仪表板对象。完成后,我需要立即更新组件中的选择下拉菜单以包含新添加的仪表板名称。 axios documentation 说应该这样做:
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?
非常感谢您的指导。
【问题讨论】:
-
试试
axios.all([this.saveDashboard(), ...等 -
呃。是的,就是这样。不敢相信我没有尝试过。谢谢。让它成为一个答案,我会标记它是正确的。
-
其实我不确定这是否是正确的方法。在我看来,当您使用 axios.all() 时,无法保证调用的执行顺序。有时有效,有时无效。
-
既然顺序很重要,就按顺序执行这两个操作-
return this.saveDashboard().then(this.getAllDashboards).then(function() {...});
标签: javascript reactjs promise es6-promise axios