我尝试通过提交编辑表单来更新帖子,然后在handleSubmit
上将我分派给了updatePost
动作创建者,但事实证明,它甚至没有交给动作创建者。直接进入控制器。我想知道为什么会发生这种情况,在这里我甚至需要执行updatePost
操作吗?另外,在将表单提交到路由/profile/:username/posts
后,它不会重定向。
这是下面的代码。
handleSubmit = () => {
const id = this.props.match.params.id
const username = this.props.auth.user.username
const postData = {
title: this.state.title,
description: this.state.description,
}
this.props.dispatch(updatePost(id, postData), () => {
this.props.history.push(`/profile/${username}/posts`)
})
}
---
export const updatePost = (id, postData, redirect) => {
return async (dispatch) => {
dispatch({ type: "UPDATING_POST_START" })
try {
const res = await axios.put(
`http://localhost:3000/api/v1/posts/${id}/edit`,
postData
)
dispatch({
type: "UPDATING_POST_START",
data: res.data,
})
redirect()
} catch (error) {
dispatch({
type: "UPDATING_POST_FAILURE",
data: { error: "Something went wrong" },
})
}
}
}
---
editPost: async (req, res, next) => {
try {
const postData = {
title: req.body.title,
description: req.body.description,
}
const post = await Post.findByIdAndUpdate(req.params.id, postData, {
new: true,
})
if (!post) {
return res.status(404).json({ message: "No post found " })
}
return res.status(200).json({ post })
} catch (error) {
return next(error)
}
}
答案 0 :(得分:0)
handleSubmit
对dispatch
一无所知。尝试像这样分发updatePost
:
handleSubmit = () => {
return dispatch => {
const id = this.props.match.params.id
const username = this.props.auth.user.username
const postData = {
title: this.state.title,
description: this.state.description,
};
dispatch(updatePost(id, postData), () => {
history.push(`/profile/${username}/posts`)
})
}
}
如果我误解了某些内容,请在使用时发送更多代码。