[英]React Redux problem on dispatching on button
我有一個按鈕可以調度一個動作來創建一個帖子,由於某種原因,請求永遠不會繼續並且它失敗了。 這就是行動。 我有常量,這就是類型不在字符串上的原因
export const createPost = () => async (dispatch, getState) => {
try {
dispatch({
type: POST_CREATE_REQUEST,
});
const {
userLogin: { userInfo },
} = getState();
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.post(
`http://localhost:5000/api/posts`,
config
);
dispatch({
type: POST_CREATE_SUCCESS,
payload: data,
});
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
// if (message === 'Not authorized, token failed') {
// dispatch(logout());
// }
dispatch({
type: POST_CREATE_FAIL,
payload: message,
});
}
};
它繼續到 POST_CREATE_REQUEST,但總是出錯到 POST_CREATE_FAIL。
我嘗試使用 postman 並且工作正常,我認為問題是即使我以管理員身份登錄,createPost 操作似乎也無法接收令牌,我不確定。
這是 postCreate 的 useSelector
const postCreate = useSelector(state => state.postCreate);
const {
loading: loadingCreate,
error: errorCreate,
success: successCreate,
post: createdPost,
} = postCreate;
這是已登錄用戶的 useSelector,當前為管理員。
const userLogin = useSelector(state => state.userLogin);
const { userInfo } = userLogin;
重寫這段代碼
const { data } = await axios.post(
`http://localhost:5000/api/posts`,
config
);
作為
const res = await axios.post(
`http://localhost:5000/api/posts`,
config
);
const data = res && res.data
我的 Controller 在后端已經有值,只需要在操作中添加括號
由此
const { data } = await axios.post(
`http://localhost:5000/api/posts`,
config
);
對此
const { data } = await axios.post(
`http://localhost:5000/api/posts`, {},
config
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.