从express成功返回承诺,但在前端与react,我如何能够使用这个承诺,在分派有效载荷,在反应状态挂钩,我想直接推送响应数据的有效载荷。不想用然后抓住。
后端
router.get('/', auth, async (req, res) => {
try {
const authUser = await Employee.findById(req.decoded.userid).select('-password');
console.log(authUser);
return res.status(200).json({ success: true, authUser });
} catch (error) {
return res.status(500).json({ success: false, msg: 'Server error' });
}
});前端
const loadUser = async () => {
try {
const response = axios.get('/api/auth');
//console.log(response)
response
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
dispatch({
type: USER_LOADED,
payload: response.data,
});
} catch (error) {
dispatch({
type: AUTH_ERROR,
});
}
};发布于 2019-12-25 03:49:02
像这样试试。
//with Redux-thunk middleware.
const loadUser = () => async (dispatch) => {
try {
const response = await axios.get('/api/auth');
dispatch({
type: USER_LOADED,
payload: response.data,
});
} catch (error) {
dispatch({
type: AUTH_ERROR,
});
}
};发布于 2019-12-25 03:49:58
由于您已经使用了异步函数,所以不能这样做:
const loadUser = async ()=>{
try {
const response = await axios.get("/api/auth");
console.log(response)
dispatch({
type:USER_LOADED,
payload:response.data
})
} catch (error) {
console.log(error)
dispatch({
type:AUTH_ERROR
})
}
}https://stackoverflow.com/questions/59474840
复制相似问题