【问题标题】:Parsing JSON response data in React action在 React 操作中解析 JSON 响应数据
【发布时间】:2016-12-29 18:45:38
【问题描述】:

我正在调用我的服务器以从第 3 方 API (Yelp) 获取一些 json 数据。我正在使用 axios 和 redux-promise 在 redux 中设置状态,以便我可以在反应中使用它。返回的数据让我很困惑。

我想将状态设置为从 Yelp API 返回的业务数据数组。目前,如果我传入一个基本字符串作为有效负载,则此操作有效。我不确定如何从 api 响应中获取此 JSON 数据,然后在 redux 状态下对其进行操作。

这是数据的样子

这是我的动作 js 文件

import axios from 'axios';

export const ZIP_CODE = 'ZIP_CODE';

const ROOT_URL = 'http://www.localhost:3000/v1/location/1/1/2/4000'


function getBusinesses(json) {  
    const business_data = json['data']['businesses']
    console.log(business_data)
    return business_data;
}


/*
 * Updates the users location
*/
export function updateZip(zipCode) {

    const request = axios.get(ROOT_URL)
    .then(getBusinesses)
    
    return {
        type: ZIP_CODE,
        payload: request
    }
}

【问题讨论】:

  • The data that gets returned is confusing me - 以什么方式?
  • @JaromandaX 我不确定如何正确地将其传递给有效负载。我将它传递给有效负载,最终结果是一个承诺对象。我构建了函数以仅返回项目数组,但仍然没有
  • 是的,但是 updateZip 被调用必须能够处理payload 是一个承诺的事实 - 恐怕超出我的范围,对redux和reduc知之甚少 -承诺提供帮助。对不起

标签: javascript json reactjs promise redux


【解决方案1】:

我为我的解决方案找到了一个修复程序,其中涉及一些尴尬的修补和修复错误。

修复 1 - 更新商店

我已经添加了 thunk 并且效果很好

  const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  const store = createStore(reducers, composeEnhancers(
    applyMiddleware(ReduxThunk)
  ));

修复 2 - 将 thunk 集成到操作中

我在初始函数中解析了 json,然后将其返回给发送到 reducer 的操作

import axios from 'axios';

export const ZIP_CODE = 'ZIP_CODE';

const ROOT_URL = 'http://www.localhost:3000/v1/location/1/1/2/4000'

function getBusinesses(res) {   

    return {
        type: ZIP_CODE,
        payload: res['data']['businesses']
    }
}

export function updateZip(zipCode) {
  return function(dispatch) {
    axios.get(ROOT_URL)
      .then((response) => {
        dispatch(getBusinesses(response))
      })
  }
}

【讨论】:

    猜你喜欢
    • 2021-07-29
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多