簡體   English   中英

與axios並發請求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM