[英]Parsing JSON response data in React action
我正在呼叫服務器,以從第三方API(Yelp)獲取一些json數據。 我正在使用axios和redux-promise在redux中設置狀態,以便可以在react中使用它。 返回的數據使我感到困惑。
我想將狀態設置為從Yelp API返回的業務數據數組。 當前,如果我傳入基本字符串作為有效負載,則此操作有效。 我不確定如何從api響應中獲取此JSON數據,然后從redux狀態做出反應。
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
}
}
我找到了解決方案的修復程序,其中涉及一些笨拙的修補工作,並最終修復了一些錯誤。
我加了thunk,效果很好
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(
applyMiddleware(ReduxThunk)
));
我在一個初始函數中解析了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))
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.