【发布时间】:2018-10-29 20:31:13
【问题描述】:
我很难弄清楚我的动作创建器中正在发生(和未发生)的事情。
我需要调用一个 API 端点,获取所有返回项目的 ID 和名称,然后为每个 ID 进行另一个调用。我想将最后一次调用的返回和第一次调用的 ids/names 存储在一个对象中并调度它。
{
category: name //name of category
subcategory: [] //array of categories in the category above.
}
现在,我的 reducer 最终得到了我想要的东西,但是当我尝试在组件中记录那个特定的 prop 时,它是空的。 (下面我使用的是 OpenSocialAPI 或 osapi。这只是 ajax 请求的基本包装。允许我不必进行身份验证,因为它看到我已经通过身份验证。)
export function fetchCategories(id){
let categories = []
return function(dispatch){
dispatch(requestCategories(id))
return osapi.core.get({
v: "v3",
href: "/places/" + id + "/places"
}).execute(function(response) {
response.content.list.forEach(function(category) {
osapi.core.get({
v: "v3",
href: "/places/" + category.id+ "/categories"
}).execute(function(response) {
categories.push({
category: category.name,
subcategories: response.content.list.map(category => category.name)
})
})
})
console.log("Category response: ", categories)
dispatch(receiveCategories(id, categories))
})
}
}
export function receiveCategories(id,array){
return {
type: RECEIVE_CATEGORIES,
id,
categories: array,
recievedAt: new Date(Date.now()),
isFetching: false
}
}
在我的应用程序中,我在 componentDidMount 中调度动作创建者
componentDidMount() {
const { dispatch } = this.props
dispatch(fetchCategoriesIfNeeded(id))
}
现在,当我控制台登录我的 Category 组件并在上面执行时,它是空的。但是在我的记录器中查看我的状态,当recieveCategories 完成时,我有我想要的对象数组
[{category:...,
subcategories:[...]
},
{category:...,
subcategories:[...]
}]
我怀疑这是因为异步的原因,但我不确定如何继续。
我尝试为基于 Promise 的调用创建自己的包装器,但我遇到了类似的问题,可能更多是因为我不确定 resolve(response) 是否是我想要的。
function httpService(path){
return new Promise(function(resolve, reject){
osapi.core.get({
v: 'v3',
href: path
}).execute(function(response, error){
if(error){
return reject(new Error("Error: ", error))
}
resolve(response)
})
})
}
export function fetchCategories(spaceId) {
let categories = []
return function(dispatch) {
dispatch(requestCategories(id))
return httpService("/places/" + id + "/places")
.then(function(response) {
response.content.list.forEach(function(category) {
fetchSubCategories("/places/" + category.id + "/categories")
.then(function(response) {
categories.push({
category: category.name,
subcategories: response
})
})
})
console.log("CATEGORIES: ", categories)
dispatch(receiveCategories(id, categories))
})
}
}
function fetchSubCategories(url){
return httpService(url)
.then(function(response){
return response.content.list.map(category => category.name)
})
}
你能看看这个并给予指导吗?另外,我调度一个基于 API 响应构建的数组是一种有效的做事方式,还是有更好的方法?谢谢
我只能找到 1 个具有类似用例的其他问题,但他们使用的是 bluebird 或类似的东西。我真的很想保留这个,除了 Redux 之外没有任何额外的东西。
【问题讨论】:
-
你使用的是 redux-thunk,对吧?
-
是的,我正在使用 redux-thunk。我的道具被正确映射,因为我正在修改以前只查看 1 层类别的动作,现在需要更深入地查看。
-
您使用的这个抓取库是什么?如果不了解
.execute()API 是什么,就很难编写代码来解决这个问题。 -
.execute 只是 osapi 的 .then。
-
如果可能的话,你应该切换到 redux-saga
标签: javascript reactjs redux react-redux