开发者问题收集

如何在 React ConfirmAlert 中重定向到另一个页面?

2020-05-15
3429

我正在开发一个 React 购物车应用。如果用户点击“清除购物车”按钮,整个购物车将被清空。在此之前,应用程序应该确认操作,因此我使用了“React Confirm Alert”。如果用户点击“是”按钮,它将清除购物车并导航到根页面(“/”)。我在互联网和 StackOverflow 上搜索,并尝试了 这里 给出的三种方法。但都不起作用。对于 this.props.history.push('/')this.props.router.push('/') 都给出了一个 TypeError,表示未定义对象,对于 useHistory() ,它说违反了 React Hooks 原则。我能做些什么来让它工作吗?提前致谢!

代码:-

import React, { useEffect, useState, Component} from 'react';

import Titles  from "../Titles";
import CartColumns from './CartColumns';
import EmptyCart  from "./EmptyCart";

import CartList from "./CartList";
import {connect} from "react-redux";
import {Link, Redirect} from "react-router-dom";
import Axios from "axios";
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css' // Import css

const mapStateToProps = ({ session, history}) => ({
    session, history
});

class Cart extends Component {

    constructor() {
        super();
        this.removeItem = this.removeItem.bind(this);
    }

    state = {
        Cart: [],
        total : 0,
        discount: 0
    };

    componentDidMount() {
        if(this.props.session.userId !== null){
            this.getItems();
        }
    }

    getItems = () => {
        //function to get the items
    };

    removeItem = (productId) => {
        //method to remove an item
    };

    clearCart = () => {

        confirmAlert({
            title: 'Clear Cart',
            message: 'Are you sure to clear the Cart?',
            buttons: [
                {
                    label: 'Yes',
                    onClick: () => {Axios.get('http://localhost:8000/api/cart/clearCart', {params:{userId: this.props.session.userId}}); 
                                    } //I want to redirect from here
                },
                {
                    label: 'No'
                }
            ]
        })
    };

    checkout= () => {
        //Checkout function
    };

    render() {
        let total = this.state.total;
        let discount = this.state.discount;

        if(this.props.session.username !== null){
            return (
                <section>
                    {(this.state.Cart.length > 0) ? (
                        <React.Fragment>
                            <Titles name ="Your " title = "Cart">Cart</Titles>
                            <CartColumns/>
                            <CartList cart = {this.state.Cart} removeItem={this.removeItem}/>
                            <div className="container">
                                <div className="row">
                                    <div className="col-10 mt-2 ml-sm-5 ml-md-auto col-sm-8 text-capitalize text-right">
                                        <h5>
                                            <span className="text-title">Sub Total: </span>
                                            <strong>$ {total}</strong>
                                        </h5>
                                        <h5>
                                            <span className="text-title">Discount: </span>
                                            <strong>$ {discount}</strong>
                                        </h5>
                                        <h5>
                                            <span className="text-title">Total: </span>
                                            <strong>$ {total - discount}</strong>
                                        </h5>


                                            <div className="col-10 mt-2 ml-sm-5 ml-md-auto col-sm-8 text-capitalize text-right">
                                                <button className="btn btn-outline-danger text-uppercase mb-3 px-5" type="button" onClick={this.clearCart}>Clear Cart</button>
                                                <button className="btn btn-outline-info ml-3 text-uppercase mb-3 px-5" type="button" onClick={this.checkout}>Check Out</button>
                                            </div>


                                    </div>
                                </div>
                            </div>
                        </React.Fragment>
                    ) : (
                        <EmptyCart/>
                        )
                    }
                </section>
            );
        } else {
            return(
                <Redirect to="/login" />
            );
        }

    }
}

export default connect(
    mapStateToProps
)(Cart);
2个回答

我认为您有 2 个选择。

第一:只需使用这样的 window.location 方法

// Simulate a mouse click:
window.location.href = "http://www.example.com";

// Simulate an HTTP redirect:
window.location.replace("http://www.example.com");

第二:使用 react 状态

import React from 'react'
import { Redirect } from 'react-router-dom'
class Cart extends Component {

    constructor() {
        super();
    }

    state = {
      isRedirect: false 
    };
    const onClick = () =>{
     this.setState({isRedirect: true})
    }
   render() {
      let isRedirect = this.state.isRedirect;
      if(isRedirect == true){
       return <Redirect to='/target' />
     }
     return (
      <div>
        ... 
      </div>
     )
   )
 }
Khayankhyarvaa Turmandakh
2020-05-15
window.location.replace("http://localhost:3000/");

此语句将解决您的问题。祝您编码愉快!

Poorna Senadheera
2022-07-19