[英]Route to URL in React component
I am creating an application which has user profiles.我正在创建一个具有用户配置文件的应用程序。 If a user decides to delete their profile (by clicking "Delete Profile" button), it should send a DELETE request to my backend server, then route the user to a "/about" page of my application.如果用户决定删除他们的个人资料(通过单击“删除个人资料”按钮),它应该向我的后端服务器发送一个 DELETE 请求,然后将用户路由到我的应用程序的“/about”页面。 The code structure I have is below:我的代码结构如下:
import React, { Component } from "react";
import { render } from "react-dom";
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
};
this.deleteProfile = this.deleteProfile.bind(this);
}
deleteProfile() {
// props contains all the necessary information to construct the request
// send request to backend server to delete the profile
// route to /about page
}
render() {
return (
<button onClick={this.deleteProfile}>Delete Profile</button>
);
}
}
export default Profile;
I haven't been able to find a solution on how to route the user to a URL after they click the Delete Button.在用户单击“删除”按钮后,我无法找到有关如何将用户路由到 URL 的解决方案。 Any suggestions on how to do this?关于如何做到这一点的任何建议?
You should be abe to make use of the Fetch API .您应该使用Fetch API 。
deleteProfile() {
// props contains all the necessary information to construct the request
const { data, url } = this.props
// ES6 and asuming you want to pass the id of in the req body
// data should looks like an obj -> { id : 'im_id000x' }
const body = { ...data }
const headers = new Headers()
const deleteURL = 'mydomain.net/profile_image' // it should have http:// or https://
const redirectURL = 'https://google.de'
headers.append('Content-Type', 'application/json')
// Assuming the API requires a DELETE method
const config = { method: 'DELETE', headers, body: JSON.stringify(body), redirect: 'follow' }
// Send request to backend server to delete the profile
fetch(`deleteURL`, config)
.then(res => res.json()) // assuming the server response is a JSON
.then(parsedRes => console.log(parsedRes))
.then(() => {
// route to /about page
window.location.href = `${redirectURL}`
})
.catch(err => console.error(err.message ? err.message : err))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.