如何在react-redux中发出HTTP请求?

我才刚开始做出反应,我有点迷茫。我正在尝试制作一个登录页面并发出一个http发布请求。现在,我只是想使任何类型的HTTP请求都能正常工作,所以我使用了请求bin,并在文档中找到了针对npm软件包的这一基本操作(https://www.npmjs.com/package/redux

-react-fetch):

export function updateTicket(ticketId, type, value){

return {

type: 'updateArticle',

url: `http://requestb.in/1l9aqbo1`,

body: {

article_id: ticketId,

title: 'New Title'

},

then: 'updateTicketFinished'

}

}

那么,写完一个动作之后,我该怎么办?我实际上如何让我的应用程序调用并使用该操作?npm软件包的文档中提到了有关在商店中设置状态的内容,这是我需要首先设置的内容吗?

回答:

您可以尝试以下任何一种方法。我都用过fetchaxios它们工作得非常好。尚未尝试superagent

  1. 对于发出请求,您可以将其fetch与fetch-polyfill一起使用,以实现所有浏览器的兼容性(link)
  2. Axios库。(链接)
  3. 具有承诺的超级代理。(链接)

如果您使用提取,则您需要使用polyfill,因为IE和Safari浏览器尚不支持它。但是使用polyfill效果很好。您可以查看链接以了解如何使用它们。

因此,您要做的就是在动作创建器中使用上述任何一种来调用API。

function fetchData(){

const url = '//you url'

fetch(url)

.then((response) => {//next actions})

.catch((error) => {//throw error})

}

 axios.get('//url')

.then(function (response) {

//dispatch action

})

.catch(function (error) {

// throw error

});

这就是为了进行API调用,现在该状态了。在redux中,有一种状态可以处理您的应用。我建议您应该阅读redux基础知识,您可以在这里找到。因此,一旦您的api调用成功,您就需要使用数据更新状态。

取数据的动作

 function fetchData(){

return(dispatch,getState) =>{ //using redux-thunk here... do check it out

const url = '//you url'

fetch(url)

.then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array

.catch( error) => {//throw error}

}

}

更新状态的动作

   function receiveData(data) {

return{

type: 'RECEIVE_DATA',

data

}

}

   function app(state = {},action) {

switch(action.types){

case 'RECEIVE_DATA':

Object.assign({},...state,{

action.data

}

})

default:

return state

}

}

以上是 如何在react-redux中发出HTTP请求? 的全部内容, 来源链接: utcz.com/qa/416697.html

回到顶部