Javascript 路由到React组件中的URL
我正在创建一个具有用户配置文件的应用程序。如果用户决定删除他们的配置文件(通过单击“删除配置文件”按钮),它应该向我的后端服务器发送删除请求,然后将用户路由到我的应用程序的“/关于”页面。我的代码结构如下:Javascript 路由到React组件中的URL,javascript,reactjs,url,routes,Javascript,Reactjs,Url,Routes,我正在创建一个具有用户配置文件的应用程序。如果用户决定删除他们的配置文件(通过单击“删除配置文件”按钮),它应该向我的后端服务器发送删除请求,然后将用户路由到我的应用程序的“/关于”页面。我的代码结构如下: import React, { Component } from "react"; import { render } from "react-dom"; class Profile extends Component { constructor
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;
import React,{Component}来自“React”;
从“react dom”导入{render};
类概要文件扩展了组件{
建造师(道具){
超级(道具);
此.state={
};
this.deleteProfile=this.deleteProfile.bind(this);
}
deleteProfile(){
//props包含构造请求所需的所有信息
//向后端服务器发送删除配置文件的请求
//发送至/关于第页
}
render(){
返回(
删除配置文件
);
}
}
导出默认配置文件;
在用户单击“删除”按钮后,我无法找到如何将用户路由到URL的解决方案。有什么建议吗?您可以利用
您使用的是什么路由器?我只是使用默认的Django路由(通过urlpatterns)。下面的答案满足了我的需要,谢谢!
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))
}