【发布时间】:2019-04-18 21:06:01
【问题描述】:
我有一个使用 Axios 的 thunk,它使用 Sequelize 发布到 Express 路由。
路由正确发布(即数据被添加到数据库中),但 React 组件内部的操作未按预期运行。使用async/await,我希望该操作等到它完成数据库发布后再继续,但这里不是这种情况。我正在从行动中获得undefined。
thunk 到达我正在调度操作以更新我的 redux 存储并返回响应的快速路由:
const addedNewList = (newList) => ({type: ADD_NEW_LIST, newList})
export const addNewList = (name, userId) => async dispatch => {
try {
const { data } = await axios.post('/api/list/add', { name, userId })
dispatch(addedNewList(data))
return data
} catch (err) {
console.error(err)
}
}
使用调试器,我可以确认return data 实际上正在从我需要的服务器返回响应。我还可以确认 redux 商店正在正确更新。
但是在这里,当我尝试以result 访问该响应数据时,我得到undefined:
handleSubmit = async () => {
const result = await this.props.addNewList(this.state.name, this.props.userId)
// ** result is 'undefined' **
this.handleClose()
// pass off the results
}
如果我在调用addNewList 操作后添加setTimeout,它会按预期工作。这向我暗示,也许它没有兑现承诺?但我的理解是,如果你在 thunk 中返回来自服务器的响应,它就会这样做。
为了完整起见,这是我的路线,我还通过调试器确认数据正在按预期传递:
const userAuth = function(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.status(401).send('Unauthorized user')
}
router.post('/add', userAuth, async (req, res, next) => {
const { name, userId } = req.body
try {
const list = await List.create({ name, userId })
res.json(list)
} catch(err) { next(err) }
})
为什么操作在handleSubmit 方法中返回undefined?
【问题讨论】:
标签: reactjs express redux sequelize.js