Raj*_*med 37 reactjs react-redux
未处理的拒绝(错误):操作必须是普通对象.使用自定义中间件进行异步操作.
详细信息:我想在每个帖子中添加评论.因此,当运行获取帖子时,我想为所有帖子调用fetch comment API.
这是我的代码:
export function bindComments(postId) {
return API.fetchComments(postId).then(comments => {
return {
type: BIND_COMMENTS,
comments,
postId
}
})
}
Run Code Online (Sandbox Code Playgroud)
谢谢
sad*_*diq 38
您必须在异步请求结束后发送.
这可行:
export function bindComments(postId) {
return function (dispatch){
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch( {
type: BIND_COMMENTS,
comments,
postId
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*lig 36
对于像我这样可能放弃简单细节的未来寻求者,在我的情况下,我只是忘记用括号调用我的动作函数。
动作.js:
export function addNewComponent() {
return {
type: ADD_NEW_COMPONENT,
};
}
Run Code Online (Sandbox Code Playgroud)
myComponent.js:
import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';
useEffect(() => {
dispatch(refreshAllComponents); // <= Here was what I've missed.
}, []);
Run Code Online (Sandbox Code Playgroud)
我忘记用(). 所以这样做解决了我的问题。
useEffect(() => {
dispatch(refreshAllComponents());
}, []);
Run Code Online (Sandbox Code Playgroud)
同样,这可能与 OP 的问题无关,但我希望我能帮助与我有同样问题的人。
Ash*_*ari 23
该错误只是要求您在中间插入一个中间件,这将有助于处理异步操作。
你可以这样做:
npm 我 redux-thunk
Inside index.js
import thunk from "redux-thunk"
...createStore(rootReducers, applyMiddleware(thunk));
Run Code Online (Sandbox Code Playgroud)
现在,异步操作将在您的函数中工作。
Sin*_*pcs 13
没有中间件,您不能在操作中使用 fetch。动作必须是普通对象。您可以使用 redux-thunk 或 redux-saga 之类的中间件来执行 fetch 然后分派另一个操作。
这是使用 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));
})
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
改变:
export const <youractionName> = async (dispatch) => {}
Run Code Online (Sandbox Code Playgroud)
到,
export const <youractionName> = () => async (dispatch) => {}
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题。错过了“() =>”
利用箭头函数提高代码的可读性。不需要返回任何东西API.fetchComments,Api 调用是异步的,当请求完成时then会得到响应,你只需要dispatch输入和数据。
下面的代码通过使用箭头函数来完成同样的工作。
export const bindComments = postId => {
return dispatch => {
API.fetchComments(postId).then(comments => {
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52480 次 |
| 最近记录: |