在 fech 之后如何使用响应作为参数从动作创建者重定向?
How can I redirect from an action creator after a fech using the response as a param?
我正在使用一个 API,returns 最后插入的 ID。另一方面,我在 Redux 上有一个动作创建器,它发出 fetch post 请求。我如何从抓取中获取响应并根据响应进行重定向?
在我的 action creator 中,我有:
export const newPostRequest = (userid, title, body, history) => {
return async (dispatch) => {
await fetch('/posts', {
method: 'POST',
headers: {
'Accept': 'Application/json',
'Content-Type': 'Application/json'
},
body: JSON.stringify({post: {user_id: userid, title: title, body: body}})
})
.then(response => response.json())
// I want to redirect from here to '/posts/:id' where id comes from the response
}
}
在我的组件中,我有:
const mapDispatchToProps = dispatch => {
return {newPost: (user, title, body) => dispatch(newPostRequest(user, title, body)) }
}
[...]
const handleSubmit = async event => {
event.preventDefault();
await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
// I know I should redirect from here, but how can I get the response from the fetch?
}
// I know I should redirect from here, but how can I get the response from the fetch?
您可以分配异步函数的结果并像使用任何其他分配一样使用它。
const handleSubmit = async event => {
event.preventDefault();
const newPostResponse = await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
redirect(newPostResponse.id); // or whatever you need to do to redirect
}
我正在使用一个 API,returns 最后插入的 ID。另一方面,我在 Redux 上有一个动作创建器,它发出 fetch post 请求。我如何从抓取中获取响应并根据响应进行重定向?
在我的 action creator 中,我有:
export const newPostRequest = (userid, title, body, history) => {
return async (dispatch) => {
await fetch('/posts', {
method: 'POST',
headers: {
'Accept': 'Application/json',
'Content-Type': 'Application/json'
},
body: JSON.stringify({post: {user_id: userid, title: title, body: body}})
})
.then(response => response.json())
// I want to redirect from here to '/posts/:id' where id comes from the response
}
}
在我的组件中,我有:
const mapDispatchToProps = dispatch => {
return {newPost: (user, title, body) => dispatch(newPostRequest(user, title, body)) }
}
[...]
const handleSubmit = async event => {
event.preventDefault();
await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
// I know I should redirect from here, but how can I get the response from the fetch?
}
// I know I should redirect from here, but how can I get the response from the fetch?
您可以分配异步函数的结果并像使用任何其他分配一样使用它。
const handleSubmit = async event => {
event.preventDefault();
const newPostResponse = await props.newPost(props.state.user.currentUser.userId, state.title, state.body)
redirect(newPostResponse.id); // or whatever you need to do to redirect
}