[英]How to get newly created post id generated from backend API after dispatch createPost action to a reducer
I can't figure out how to get new post id after dispatch the post object to reducer through middleware thunk.通过中间件 thunk 将帖子 object 发送到减速器后,我无法弄清楚如何获取新的帖子 ID。 If could get new post id, I want to redirect to new post page by history.push(
/${newPost_id}
).如果可以获得新的帖子 ID,我想通过 history.push(
/${newPost_id}
) 重定向到新的帖子页面。 my code is:我的代码是:
backend controller:后端 controller:
export const addFilm = async (req, res) => {
const film = req.body
try {
const newFilm = new Film(film)
console.log(newFilm)
await newFilm.save()
res.status(201).json(newFilm)
} catch (error) {
res.status(409).json({message: error.message})
}
}
frontend event handleSubmit:前端事件句柄提交:
const handleSubmit = (e) => {
e.preventDefault()
dispatch(addFilm(filmData))
history.push(`/${newPost_id}`)//how to implement this?
}
}
actions:行动:
I'm going to assume that your backend returns a complete film object which has the id
property added to it.我将假设您的后端返回完整的电影 object,其中添加了
id
属性。
The redux-thunk middleware changes the behavior of dispatch
such that it returns the value that was returned from your thunk. redux-thunk 中间件改变了
dispatch
的行为,使它返回从你的 thunk 返回的值。 You will want to design your addFilm
thunk such that it dispatches the correct actions and also returns the newFilm
that it got from the backend.您将需要设计您的
addFilm
thunk 以便它调度正确的操作并返回它从后端获得的newFilm
。
Then you can modify your handler like so:然后你可以像这样修改你的处理程序:
const handleSubmit = async (e) => {
e.preventDefault();
const newFilm = await dispatch(addFilm(filmData));
history.push(`/${newFilm.id}`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.