2017-08-28 53 views
1

我正在尝试学习React,并且我正在与Axios一起进行XHR API调用。就像我所做的一切一样,首先要做的就是阅读文档。我按照以下文档实施了XHR呼叫:https://github.com/svrcekmichal/redux-axios-middleware#dispatch-actionReact Axios捕获不触发

不知何故,当请求失败时,将触发.then()子句而不是.catch子句。

我正在为什么会出问题而喋喋不休,我无法弄清楚。下面还有我是如何实现爱可信:

App.js:

const client = axios.create({ 
    baseURL:'http://localhost:8080/api', 
    responseType: 'json' 
}); 

const axiosMiddle = axiosMiddleware(client) 
const createStoreWithMiddleware = applyMiddleware(thunk, axiosMiddle)(createStore) 

Component.js:

handleLogin(event) { 
    const credentials = { 
    username: this.state.username, 
    password: this.state.password 
    } 
    this.props.login(credentials) 
    .then((response) => { 
     console.log(response) 
     console.log('SUCCESS') 
    }) 
    .catch((response) => { 
     console.log('ERROR') 
    }) 
} 

Action.js:

export function login(credentials) { 
    return { 
    type: ['LOAD','AWESOME','OH_NO'], 
    payload: { 
     request: { 
     url: '/login/', 
     method: 'POST', 
     data: { 
      username: credentials.username, 
      password: credentials.password 
     } 
     } 
    } 
    } 
} 

而执行console.log输出:

HTTP Failure in Axios Error: Network Error 
    at createError (createError.js:16) 
    at XMLHttpRequest.handleError (xhr.js:87) 
Root.jsx:82 {type: "LOAD,AWESOME,OH_NO_FAIL", error: {…}, meta: {…}}error: {data: "Network Error", status: 0}meta: {previousAction: {…}}type: "LOAD,AWESOME,OH_NO_FAIL"__proto__: Object 
Root.jsx:83 SUCCESS 

慢慢地我疯了,不知何故我不知道如何解决它。有人能帮助我吗?

回答

1

在component.js中,您的登录不会执行任何异步调用,而只是返回一个对象,不会发生任何错误,这就是为什么它总是以“成功”结尾。而console.log(response)总是打印登录返回的对象。

因此,不是简单地返回对象,而应该实际执行异步请求。实际执行请求的方式是dispatch(login(credentials))

顺便说一句,你得到的错误与登录无关,它发生在App.js中的axios.create。

+0

感谢您的解释。我在想如何处理错误的动作,但是我希望我能通过学习来解决它。 感谢您的帮助。 – nobody