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

How do I make an HTTP request in react-redux?

我刚刚开始使用 React,我有点迷茫。我正在尝试制作登录页面并发出 http post 请求。现在我只是想让任何类型的 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 库。 (link)
  3. 有承诺的超级代理人。(link)

如果您使用 fetch,则需要使用 polyfill,因为 IE 和 safari 尚不支持它。但是使用 polyfill 它工作得很好。您可以查看链接以了解如何使用它们。

所以你要做的是在你的动作创建器中,你可以使用上述任何方法调用 API。

FETCH

function fetchData(){
    const url = '//you url'
    fetch(url)
    .then((response) => {//next actions})
    .catch((error) => {//throw error})
}

AXIOS

 axios.get('//url')
  .then(function (response) {
    //dispatch action
  })
  .catch(function (error) {
    // throw error
  });

这就是 API 电话,现在进入状态。在 redux 中,有一种状态可以处理您的应用程序。我建议你应该通过 redux 基础知识,你可以找到 here 。因此,一旦您的 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
      }
   }