React-Redux:操作必须是普通对象。使用自定义中间件进行异步操作
问题描述:
未处理的拒绝(错误):操作必须是普通对象。使用自定义中间件进行异步操作。React-Redux:操作必须是普通对象。使用自定义中间件进行异步操作
详情:我想为每个帖子添加评论。因此,当抓取帖子运行时,我想调用所有帖子的抓取评论API。
这里是我的代码:
export function bindComments(postId) {
return API.fetchComments(postId).then(comments => {
return {
type: BIND_COMMENTS,
comments,
postId
}
})
}
感谢
答
您将在ansyc请求结束后发送。
这会工作:我已经使用
export function bindComments(postId) {
return function (dispatch){
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
})
})
}
}
答
不能使用在动作取不中间件。操作必须是普通对象。您可以使用像redux-thunk或redux-saga这样的中间件来执行提取操作,然后分派另一个操作。
以下是使用redux-thunk中间件的异步操作示例。
export function checkUserLoggedIn (authCode) {
let url = `${loginUrl}validate?auth_code=${authCode}`;
return dispatch => {
return fetch(url,{
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}
)
.then((resp) => {
let json = resp.json();
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})
.then(
json => {
if (json.result && (json.result.status === 'error')) {
dispatch(errorOccurred(json.result));
dispatch(logOut());
}
else{
dispatch(verified(json.result));
}
}
)
.catch((error) => {
dispatch(warningOccurred(error, url));
})
}
}
+0
终极版 - 咚 –
+0
对不起,我以为你没有使用中间件。那是@sadiq提到它的问题。 – SNT
它像魅力一样工作。谢谢 –