繁体   English   中英

从下拉列表中获取数据以进行动态调用 api

[英]get data from dropdown for dynamic call api

所以我使用 redux-hooks 进行 state 管理,所以在我的应用程序中有一个下拉列表,该值将用于动态调用 api,在动作创建者中我是这样制作的

export const getFetchCasesSelectedCountry = (country) => (dispatch) => {
return (
  axios.get(`https://covid19.mathdro.id/api/countries/${country}`).then((result) => {
    let confirmed = result.data.confirmed.value;
    let recovered = result.data.recovered.value;
    let death = result.data.deaths.value;

    dispatch({
      type: GET_SELECTED_COUNTRY,
      payload: {
        countryConfirmed: confirmed,
        countryRecovered: recovered,
        countryDeath: death,
      }
    })
  })
 )
}

但我收到了这个错误

如何从下拉列表中获取值以便可以将其输入到动作创建者中? 可能吗? 抱歉,如果我的问题难以理解。

HTTP 错误 404,或更通常称为“404 错误”,表示在服务器上找不到您尝试使用的 api。 这是客户端事件,这意味着端点已被删除或移动,并且 URL 尚未相应修改,或者您拼错了 URL。

阅读此内容以获取更多信息

404 问题可能有多种原因:

  • 这可能是网络问题 - 我的意思是您的环境无法访问请求的 URL。 我从代码中看到您执行 GET 请求,因此要测试网络,您只需使用操作中使用的 URL 打开浏览器即可。 例如https://covid19.mathdro.id/api/countries/USA

  • 调用getFetchCasesSelectedCountry的代码提供了一些奇怪的国家/地区值,可能导致 404 错误

尽管如此,您发布的代码不处理可能由 axios 调用(例如 404)引起的错误,因此您的商店不会意识到可能发生的错误,因此连接到商店的组件也不会请注意此类问题。

根据我的经验,使用 redux 处理此类事情的常用方法是引入更多状态,这将存储错误信息:

// this is purely an example
// let say that you have such state
const state = {
    loading: false,
    hasError: false,
    errorMessage: '',
    data: null,
}

// reducer
function stateReducer(state, action) {
    switch(action.type) {
        case GET_SELECTED_COUNTRY_LOAD:
            // set here 'loading' to true - started request execution
            // return new state
        case GET_SELECTED_COUNTRY_LOADED:
            // set here 'loading' to false - got response
            // set here data that came with action payload
            // return new state
        case GET_SELECTED_COUNTRY_FAILED:
            // set here 'loading' to false - got error response or failed
            // sethere 'errorMessage' that came with action payload 
            // return new state
    }
}

// you'll have to create 2 new action creators to handle GET_SELECTED_COUNTRY_LOAD // and GET_SELECTED_COUNTRY_FAILED

// now your code should look like this
const getFetchCasesSelectedCountry = (country) => (dispatch) => {
return (
  dispatch({ type: GET_SELECTED_COUNTRY_LOAD });
  axios.get(`https://covid19.mathdro.id/api/countries/${country}`)
     .then((result) => {
         // do some stuff with result
         dispatch({
              type: GET_SELECTED_COUNTRY_LOADED,
              payload: { /* useful data here */ }
         });
      ).catch(err => {
           dispatch({
              type: GET_SELECTED_COUNTRY_FAILED,
              payload: { /* useful error data here */ }
           });
      })
}

因此,每当发生错误时,连接到 store 的组件将能够处理它(至少显示可以从 store 获取的 errorMessage)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM