react中 如何異步展示后台接口的提示消息


調用接口后,后台會返回這樣的一段信息提示:{"errCode":400002,"errMsg":"字段校驗異常","data":{"jzq":"日期不能為空","cfmc":"名稱不能為空","jdrq":"決定日期不能為空","cflb1":"類別1不能為空"}}

先補充點一些其他的知識:

關於axios(以前用的jquer的ajax請求,現在大都推崇axios來代替)

參考地址:http://www.tuicool.com/articles/yINjEb6

執行 POST 請求

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

項目框架用到的技術組合:

1.react+ant design+react-router+redux(關於每個框架具體是怎么用和用來做什么的還請自己查閱相關文檔)

2. 使用 immutable state

3.使用 Classes

React 與 ES2015 的 Class 語法搭配的很好.

class HelloMessage extends React.Component {

render() {

return

Hello {this.props.name}

} }

4.打包編譯工具:babel

 
        

下面進入今天的主題:一個業務場景是這樣的,我有一個表單,我正在編輯該表單的某些字段,然后當我點擊“保存”按鈕的時候,執行保存,成功提示“保存成功”,如果失敗,需要提示后台返回的錯誤消息:具體是那個字段出問題了。

現在回到我的代碼上來,其實這個功能按照傳統的jQuery模式很簡單,ajax后分success或者erro就可以做操作了!在react中,在看看應該如何來實現:

 handleSubmit = (e) => {

        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                console.error(errors);
                return;
            }

            const payload = {...this.props.xkObj, ...values};
        //調用執行修改函數
this.props.xzxkService.updateXzxk(payload) .then(data=> { console.log('data', data); Utils.pushLink('/reporting/xxxx') }) .catch(error=> {
            //當有錯誤消息是提示錯誤消息 const err
= {errCode: error.errCode, errMsg: error.errMsg, data: error.data}; console.log('err', err); let hlresultMessage =""; hlresultMessage +='錯誤消息:'; if (err) { for(let i in err.data){ hlresultMessage +=err.data[i]+',';//組裝這個對象,拼接錯誤消息 } //alert(hlresultMessage); Modal.error({//使用模態框的error模式,需要引入對應的組件 title:'錯誤消息', content:hlresultMessage }) } }); }); };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM