【问题标题】:Route to URL in React component路由到 React 组件中的 URL
【发布时间】:2020-10-15 19:01:12
【问题描述】:

我正在创建一个具有用户配置文件的应用程序。如果用户决定删除他们的个人资料(通过单击“删除个人资料”按钮),它应该向我的后端服务器发送一个 DELETE 请求,然后将用户路由到我的应用程序的“/about”页面。我的代码结构如下:

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;

在用户单击“删除”按钮后,我无法找到有关如何将用户路由到 URL 的解决方案。有关如何执行此操作的任何建议?

【问题讨论】:

  • 你用的是什么路由器?
  • 我只是使用默认的 Django 路由(通过 urlpatterns)。下面的答案做了我需要的,谢谢!

标签: javascript reactjs url routes


【解决方案1】:

您应该使用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))
  }

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    相关资源
    最近更新 更多