使用fetch

时间:2017-08-10 01:00:04

标签: javascript reactjs redux react-redux fetch-api

我正在开发一个React应用程序,我无法通过在应用程序发送的每个查询中添加access_token参数来找到一种“干净”的方式来自动验证API调用。访问令牌存储在redux store

我创建了一个处理所有API调用的lib文件:

const api_server = 'http://site.dev/'
const api_url = api_server + '/app/api'
const api_version = 'v1'
const client_id = '1_xxxxxxxxxxxxxxx'
const client_secret = 'xxxxxxxxxxxxxxxx'

module.exports = {

  getRealtimeFeed: function(page, access_token=''){
    const endpoint = api_url + '/' + api_version + '/posts?'
      + 'limit=6'
      + '&page=' + page
      + '&access_token=' + access_token
    return fetch(
      endpoint,
      { method: "GET", headers: { "Accept": "application/json" }}
    )
  },
}

我觉得在整个应用程序中使用很容易,除了你可以看到,我总是需要将访问令牌传递给api函数。

然后我在我的actionCreators.js文件中使用该api

import SiteAPI from '../lib/site.api'

export function fetchLatestPosts(page, accessToken='') {
  return dispatch => {
    SiteAPI.getRealtimeFeed(page, accessToken)
    .then( (response) => {
      if (response.status === 200){
        response.json().then( (json) => {
          dispatch(fetchedLatestsPosts(json.results))
        })
      } else {
        console.error(response)
      }
    })
  }
}

在我的反应Component中,我使用访问令牌调用了action函数,但这意味着我的所有组件都需要将访问令牌作为prop传递。

我想知道是否有办法一次性设置访问令牌以供api使用它,而不是每次我进行API调用时都必须传递它。 我很反应和反应所以可能有一个我没有正确学习的概念可以让我做这样的事情,我想。

谢谢:)

1 个答案:

答案 0 :(得分:0)

您可以在API文件中导入redux商店并使用它来检索access_token

import store from './path/to/your/store'

const api_server = 'http://site.dev/'
...

function getAccessToken() {
  return store.getState().access_token // adjust according to your store structure
}

module.exports = {
  getRealtimeFeed: function(page){
    const endpoint = api_url + '/' + api_version + '/posts?'
      + 'limit=6'
      + '&page=' + page
      + '&access_token=' + getAccessToken()
    return fetch(
      endpoint,
      { method: "GET", headers: { "Accept": "application/json" }}
    )
  },
}

修改

如果您使用的是redux-thunk,那么您可以在行动中获得access_token(您可以在getState动作函数中定义第二个参数redux-thunk):

import SiteAPI from '../lib/site.api'

export function fetchLatestPosts(page) {
  return (dispatch, getState) => {
    const accessToken = getState().accessToken
    SiteAPI.getRealtimeFeed(page, accessToken)
    .then( (response) => {
      if (response.status === 200){
        response.json().then( (json) => {
          dispatch(fetchedLatestsPosts(json.results))
        })
      } else {
        console.error(response)
      }
    })
  }
}

我认为这是更好的决定,因为您的API方法不应包含redux存储逻辑。他们应该只打扰API请求。

相关问题