使用 getState 访问 redux 状态下的密钥以进行 API 调用

Use getState to access key in redux state for API call

我对使用 thunk getState 有点陌生,我什至尝试 console.log 该方法但一无所获。在状态下,我看到 loginReducer 有他们的键 属性 我需要进行 API 调用。 status(pin): true key(pin): "Ls1d0QUIM-r6q1Nb1UsYvSzRoaOrABDdWojgZnDaQyM"

我这里有一个服务:

import axios from 'axios'
import {thunk, getState} from 'redux-thunk'
import MapConfig from '../components/map/map-config'

const origin = 'https://us.k.com/'



class KService {

  getNorthAmericaTimes() {
    return (dispatch, getState) => {
      const key = getState().key
      console.log('This is time key,', key)
      if (key) {
        dispatch(axios.get(`${origin}k51/api/datasets/k51_northamerica?key=${key}`))
      }
    }
    // const url = `${origin}k51/api/datasets/k51_northamerica?key=${urlKey}`
    // return axios.get(url)
  }
}

export default new K51Service()

但是在我的相应操作中我得到 Uncaught TypeError: _kService2.default.getNorthAmericaTimes(...).then is not a function

动作函数是这样的:

export function getKNorthAmericaTime(dispatch) {
  KService.getNorthAmericaTimes().then((response) => {
    const northAmericaTimes = response.data[0]
    dispatch({
      type: ActionTypes.SET_NORTH_AMERICA_TIMES,
      northAmericaTimes
    })
  })
}

我假设这可能与未执行 if 块有关。

你应该将你的 axios.get() 方法移动到你的 action creator,并将承诺传递给 redux thunk,然后当承诺被解决时,使用响应数据调度 action,这样它就可以被 reducer 处理到应用的状态。

动作

import axios from "axios";

export function fetchData() {
  return (dispatch, getState) => {
    const key = getState().key;
    const request = axios.get();// use your request code here
    request.then(({ response}) => {
      const northAmericaTimes = response.data[0]
      dispatch({ type: ActionTypes.SET_NORTH_AMERICA_TIMES, payload: northAmericaTimes});
    });
  };
}

这是一个将 axios 与 redux-thunk 结合使用的非常简单的示例:

https://codesandbox.io/s/z9P0mwny

编辑

抱歉,我完全忘记了您需要先去状态才能提出请求。

如您所见,转到函数中的状态,从中获取密钥,发出请求,当承诺得到解决时,使用响应数据分派操作。我已经更新了实时示例,因此您可以看到它正在运行。

再次抱歉...