【问题标题】:Use getState to access key in redux state for API call使用 getState 访问 redux 状态下的 key 以进行 API 调用
【发布时间】:2018-01-10 10:13:01
【问题描述】:

我对使用 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 块没有被执行有关。

【问题讨论】:

    标签: reactjs axios redux-thunk


    【解决方案1】:

    您应该将您的axios.get() 方法移动到您的操作创建者并将承诺传递给redux thunk,然后当承诺解决时,使用响应数据分派操作,以便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

    编辑

    对不起,我完全忘记了你需要在提出请求之前进入该州。

    如您所见,转到您的函数中的状态,从中获取密钥,发出请求,当承诺得到解决时,使用响应数据调度操作。我已经更新了实时示例,以便您可以看到它的工作原理。

    再次抱歉...

    【讨论】:

    • 我认为这不能解决使用正确 url 发出 get 请求的问题,我需要使用 getState().key 并将其保存到 url 的变量中。
    • 我已经更新了答案的代码。请再检查一遍
    • 没问题,所以我可能会遗漏一些东西我确实注释掉了原始的 getKNorthAmericaTime(dispatch) 函数然后在 home.js 组件中我更改了 mapDispatchToProps 中的函数名称,因为我在服务中进行了您建议的更改函数``` mapDispatchToProps(dispatch) { return { getKNorthAmericaTime: () => getNorthAmericaTimes(dispatch), h), }; }``` 如果你想让我把 home 组件也放在那里,请告诉我。谢谢!
    • 我假设您至少有两个动作创建者,一个用于获取登录信息,另一个用于使用 axios 和密钥获取数据。当用户登录时,您可以调用该函数以使用来自 react-redux 的 connect 从服务器获取数据,然后使用 redux-thunk 等待 promise 被解析。另外,如果您可以在代码和框中创建一个简单的简化示例,以便更好地查看您的主要组件和您的操作文件,那将非常有用。
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2022-06-24
    • 2016-06-01
    • 2017-12-26
    相关资源
    最近更新 更多