异步 – Redux Actions必须是普通对象.使用自定义中间件进行异步
发布时间:2020-12-15 20:31:42 所属栏目:百科 来源:网络整理
导读:我收到错误“Redux Actions必须是普通对象.使用自定义中间件进行异步操作.”使用以下代码. export const getFriends = () = async(): Action = { const requestConfig = { httpMethod: 'GET',version: 'v2.7',}; let hasMore = false; let friends = []; do
我收到错误“Redux Actions必须是普通对象.使用自定义中间件进行异步操作.”使用以下代码.
export const getFriends = () => async(): Action => { const requestConfig = { httpMethod: 'GET',version: 'v2.7',}; let hasMore = false; let friends = []; do { const infoRequest = new GraphRequest( '/me/friends',requestConfig,(error,result) => { if (error) { alert('Error fetching data facebook friends'); } else { result.data.forEach((value) => { friends.push(value) }); if (result.paging && result.paging.next) { hasMore = true; requestConfig.parameters.after = result.paging.cursors.after; } else { hasMore = false; } } }); await new GraphRequestManager().addRequest(infoRequest).start(); } while (hasMore); return { type: 'GET_FRIENDS',payload: friends // this is empty because there is no await on GraphAPI }; }; 如果我删除了异步并等待,那么返回的朋友是空的,因为在返回GraphAPI调用之前返回了函数调用 export const getFriends = () => (): Action => { const requestConfig = { httpMethod: 'GET',result) => { if (error) { alert('Error fetching data facebook friends'); } else { result.data.forEach((value) => { friends.push(value) }); if (result.paging && result.paging.next) { hasMore = true; requestConfig.parameters.after = result.paging.cursors.after; } else { hasMore = false; } } }); new GraphRequestManager().addRequest(infoRequest).start(); } while (hasMore); return { type: 'GET_FRIENDS',payload: friends // this is empty because there is no await on GraphAPI }; }; 解决方法
错误意味着它听起来是什么样的. Redux期待一个普通的对象.我看到用redux-thunk标记的问题.如果你正在使用redux-thunk,也许你没有正确设置中间件的商店.如果您没有使用redux-thunk,那么我会推荐它作为调度异步操作的首选库.
这将为您提供有关调度非常规对象的redux操作的深刻见解. 编辑:你错过了实际的调度,并试图简单地返回普通对象…需要返回一个调度……类似于以下内容(没有测试,但应该让你关闭): export const getFriends = () => { return (dispatch) => { const requestConfig = { httpMethod: 'GET',}; let hasMore = false; let friends = []; do { const infoRequest = new GraphRequest( '/me/friends',result) => { if (error) { alert('Error fetching data facebook friends'); } else { result.data.forEach((value) => { friends.push(value) }); if (result.paging && result.paging.next) { hasMore = true; requestConfig.parameters.after = result.paging.cursors.after; } else { hasMore = false; return dispatch({ type: 'GET_FRIENDS',payload: friends }); } } }); await new GraphRequestManager().addRequest(infoRequest).start(); } while (hasMore); } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |