Reactjs 导航离开时,反应状态恢复为上一状态

Reactjs 导航离开时,反应状态恢复为上一状态,reactjs,Reactjs,我目前正在构建一个React电子商务应用程序,但在获取真实购物车总数方面遇到了困难 将项目添加到购物车时,购物车总金额中包含以下项目: addItem() { inCart.push(this.props.id); cartColors.push({ item: this.props.id, color: this.state.color, size: this.state.size }); cartTotal += (this.props.pr

我目前正在构建一个React电子商务应用程序,但在获取真实购物车总数方面遇到了困难

将项目添加到购物车时,购物车总金额中包含以下项目:

 addItem() {
        inCart.push(this.props.id);
        cartColors.push({ item: this.props.id, color: this.state.color, size: this.state.size });
        cartTotal += (this.props.price);
        this.setState({ show: false });
    }

export let cartTotal = 0;
然后在购物车中,我有以下内容:

import { inCart, cartTotal, cartColors } from '../PageItem/PageItem.js';


class Cart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cartList: inCart,
            finalTotal: cartTotal.toFixed(2)
        }
    }

    removeItem(itemId, itemPrice) {
        var itemIndex = this.state.cartList.indexOf(itemId);
        var newList = inCart.splice(itemIndex, 1);
        var newTotal = (this.state.finalTotal - itemPrice).toFixed(2);
        this.setState({ cartList: newList, finalTotal: newTotal });
    }

问题是-当我第一次去购物车,它的工作。我根据购物车中当前的项目看到了真实的总数,当我删除这些项目时,总数会正确更新。但是,当我离开购物车并添加更多项目,然后导航回购物车时,我会看到以前的购物车总数(第一次查看购物车时显示的总数)

我尝试在removeItem函数中更新cartTotal,如下所示:

var newTotal = (cartTotal - itemPrice).toFixed(2);
和使用

this.setState({ cartList: newList, finalTotal: newTotal });
但这提供了一个关闭的总数。喜欢它将正确地加起来,但一旦我开始删除项目,它就会变得很怪。它将删除该项目,并在第一次正确更新价格,但在第二次删除时,总额将恢复为以前的全部总额,并从中删除价格-因此它关闭

如何获得永久更新的总数

以下是完整的组件:

PageItem组件:

//Dependencies
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Card, Button, Modal, Row, Container, Col } from 'react-bootstrap';
import PhotoSlider from '../../PhotoSlider/PhotoSlider.js';
import './PageItem.css';
import ColorButton from '../../ColorButton/ColorButton.js';
import SizeButton from '../../SizeButton/SizeButton.js';

class PageItem extends Component {
    constructor(props, context) {
        super(props, context);

        this.handleShow = this.handleShow.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.addItem = this.addItem.bind(this);
        this.changeColor = this.changeColor.bind(this);
        this.changeSize = this.changeSize.bind(this);

        this.state = {
            show: false,
            color: 1,
            selectedColor: '',
            size: 0
        };
    }

    changeColor(colorId) {
        this.setState({ color: colorId });
    }

    changeSize(sizeId) {
        this.setState({ size: sizeId });
    }

    handleClose() {
        this.setState({ show: false, color: 1 });
    }

    handleShow() {
        this.setState({ show: true });
    }

    addItem() {
        inCart.push(this.props.id);
        cartColors.push({ item: this.props.id, color: this.state.color, size: this.state.size });
        cartTotal += (this.props.price);
        this.setState({ show: false });
    }

    render() {
        return (
            <div className="item">
                <Card style={{ minWidth: '18rem' }} className="PageItem-Card" onClick={this.handleShow}>
                    <Card.Img className="PageItem-Card-Img" variant="top" src={this.props.img} />
                    <Card.Body className="PageItem-Card-Body">
                        <Card.Title className="PageItem-Title">{this.props.name}</Card.Title>
                        <Card.Text className="PageItem-Price">
                            {this.props.price}
                        </Card.Text>
                        <button className="PageItem-Button">Quick View</button>
                    </Card.Body>
                </Card>
                <Modal dialogClassName="custom-dialog" show={this.state.show} onHide={this.handleClose}>
                    <Modal.Header closeButton>
                        <Modal.Title>{this.props.name}</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Row>
                            <Col>
                                {this.props.colors.map((color) => {
                                    if (color.colorId === this.state.color) {
                                        return (
                                            <div>
                                                <PhotoSlider className="Modal-PhotoSlider"
                                                    img1={color.img1}
                                                    img2={color.img2}
                                                    img3={color.img3}
                                                    img4={color.img4}
                                                    img5={color.img5} />
                                            </div>
                                        )
                                    }
                                })}
                                <div className="PageItem-ColorButton-Options">
                                    {this.props.colors.map((color) => {
                                        return (
                                            <div className="PageItem-ColorButton">
                                                <ColorButton
                                                    colorId={color.colorId}
                                                    colorName={color.colorName}
                                                    colorHex={color.colorHex}
                                                    colorImg={color.colorImg}
                                                    onClick={this.changeColor}
                                                />
                                            </div>)
                                    })}
                                </div>
                                {this.props.colors.map((color) => {
                                    if (color.colorId === this.state.color) {
                                        this.setState.selectedColor = color.colorName;
                                        return (
                                            <div>
                                                <p>{color.colorName}</p>
                                            </div>
                                        )
                                    }
                                })}
                                <div className="PageItem-SizeButton-Options">
                                    {this.props.sizes.map((size) => {
                                        return (
                                            <div className="PageItem-SizeButton">
                                                <SizeButton
                                                    sizeId={size.sizeId}
                                                    sizeValue={size.sizeValue}
                                                    onClick={this.changeSize}
                                                />
                                            </div>)
                                    })}
                                </div>
                            </Col>
                            <Col>
                                <p>{this.props.description}</p>
                            </Col>
                        </Row>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="secondary" onClick={this.handleClose}>
                            Close
          </Button>
                        <Link to={`/products/${this.props.id}`}><Button variant="secondary">See More</Button></Link>
                        <Button variant="primary" onClick={this.addItem}>
                            Add to Cart
          </Button>
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}

export let inCart = [];

export let cartColors = [];

export let cartTotal = 0;


export default PageItem;
import React, { Component } from 'react';
import { Col, Row } from 'react-bootstrap';
import { inCart, cartTotal, cartColors } from '../PageItem/PageItem.js';
import CartItem from '../CartItem/CartItem.js';
import Products from '../../productData.js';
import Navbar from '../../Navbar/Navbar.js';
import Footer from '../../Footer/Footer.js';
import CartImg from '../../Images/SVG/cart2.svg';


class Cart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cartList: inCart,
            finalTotal: cartTotal.toFixed(2)
        }
    }

    removeItem(itemId, itemPrice) {
        var itemIndex = this.state.cartList.indexOf(itemId);
        var newList = inCart.splice(itemIndex, 1);
        var newTotal = (this.state.finalTotal - itemPrice).toFixed(2);
        this.setState({ cartList: newList, finalTotal: newTotal });
    }

    render() {
        console.log(this.state.finalTotal);
        return (
            <div className="Page">
                <Navbar />
                <div className="Cart">
                    <img src={CartImg}></img>
                    <h1>Shopping Cart</h1>
                    <div className="Cart-Items">
                        {Products.map((product) => {
                            var productId = cartColors.find(item => item.item === product.id);
                            if (inCart.includes(product.id)) {
                                return (
                                    <Row middle="xs" className="Cart-CartItem">
                                        <Col xs={6}>
                                            <CartItem
                                                id={product.id}
                                                name={product.name}
                                                img={product.img}
                                                description={product.description}
                                                price={product.price}
                                            /></Col>
                                        <Col xs={6}>
                                            <div className="Cart-CartOptions">
                                                {product.colors.map((color) => {
                                                    if (productId.color === color.colorId) {
                                                        return (
                                                            <div>
                                                                <p>{color.colorName}</p>
                                                            </div>
                                                        )
                                                    }
                                                })}
                                                {product.sizes.map((size) => {
                                                    if (productId.size === size.sizeId) {
                                                        return (
                                                            <div>
                                                                <p>{size.sizeValue}</p>
                                                            </div>
                                                        )
                                                    }
                                                })}
                                                <button onClick={() => this.removeItem(product.id, product.price)}>Remove</button>
                                            </div></Col>
                                    </Row>
                                )
                            }
                        })}
                    </div>
                    <div className="Cart-Total">
                        <h1>{this.state.finalTotal}</h1>
                    </div>
                </div>
                <Footer />
            </div>
        )
    }
}


export default Cart;
//依赖项
从“React”导入React,{Component};
从'react router dom'导入{Link};
从“react bootstrap”导入{Card、Button、Modal、Row、Container、Col};
从“../../PhotoSlider/PhotoSlider.js”导入PhotoSlider;
导入“./PageItem.css”;
从“../../ColorButton/ColorButton.js”导入ColorButton;
从“../../SizeButton/SizeButton.js”导入SizeButton;
类PageItem扩展组件{
构造函数(道具、上下文){
超级(道具、背景);
this.handleShow=this.handleShow.bind(this);
this.handleClose=this.handleClose.bind(this);
this.addItem=this.addItem.bind(this);
this.changeColor=this.changeColor.bind(this);
this.changeSize=this.changeSize.bind(this);
此.state={
秀:假,,
颜色:1,
所选颜色:“”,
尺寸:0
};
}
更改颜色(颜色ID){
this.setState({color:colorId});
}
更改大小(大小ID){
this.setState({size:sizeId});
}
handleClose(){
this.setState({show:false,color:1});
}
handleShow(){
this.setState({show:true});
}
附加项(){
invot.push(this.props.id);
push({item:this.props.id,color:this.state.color,size:this.state.size});
cartTotal+=(this.props.price);
this.setState({show:false});
}
render(){
返回(
{this.props.name}
{this.props.price}
快速查看
{this.props.name}
{this.props.colors.map((color)=>{
if(color.colorId==this.state.color){
返回(
)
}
})}
{this.props.colors.map((color)=>{
返回(
)
})}
{this.props.colors.map((color)=>{
if(color.colorId==this.state.color){
this.setState.selectedColor=color.colorName;
返回(
{color.colorName}

) } })} {this.props.size.map((size)=>{ 返回( ) })} {this.props.description}

接近 查看更多 添加到购物车 ); } } export-let-intranet=[]; 导出颜色=[]; 出口总额=0; 导出默认页面项;
购物车组件:

//Dependencies
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Card, Button, Modal, Row, Container, Col } from 'react-bootstrap';
import PhotoSlider from '../../PhotoSlider/PhotoSlider.js';
import './PageItem.css';
import ColorButton from '../../ColorButton/ColorButton.js';
import SizeButton from '../../SizeButton/SizeButton.js';

class PageItem extends Component {
    constructor(props, context) {
        super(props, context);

        this.handleShow = this.handleShow.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.addItem = this.addItem.bind(this);
        this.changeColor = this.changeColor.bind(this);
        this.changeSize = this.changeSize.bind(this);

        this.state = {
            show: false,
            color: 1,
            selectedColor: '',
            size: 0
        };
    }

    changeColor(colorId) {
        this.setState({ color: colorId });
    }

    changeSize(sizeId) {
        this.setState({ size: sizeId });
    }

    handleClose() {
        this.setState({ show: false, color: 1 });
    }

    handleShow() {
        this.setState({ show: true });
    }

    addItem() {
        inCart.push(this.props.id);
        cartColors.push({ item: this.props.id, color: this.state.color, size: this.state.size });
        cartTotal += (this.props.price);
        this.setState({ show: false });
    }

    render() {
        return (
            <div className="item">
                <Card style={{ minWidth: '18rem' }} className="PageItem-Card" onClick={this.handleShow}>
                    <Card.Img className="PageItem-Card-Img" variant="top" src={this.props.img} />
                    <Card.Body className="PageItem-Card-Body">
                        <Card.Title className="PageItem-Title">{this.props.name}</Card.Title>
                        <Card.Text className="PageItem-Price">
                            {this.props.price}
                        </Card.Text>
                        <button className="PageItem-Button">Quick View</button>
                    </Card.Body>
                </Card>
                <Modal dialogClassName="custom-dialog" show={this.state.show} onHide={this.handleClose}>
                    <Modal.Header closeButton>
                        <Modal.Title>{this.props.name}</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Row>
                            <Col>
                                {this.props.colors.map((color) => {
                                    if (color.colorId === this.state.color) {
                                        return (
                                            <div>
                                                <PhotoSlider className="Modal-PhotoSlider"
                                                    img1={color.img1}
                                                    img2={color.img2}
                                                    img3={color.img3}
                                                    img4={color.img4}
                                                    img5={color.img5} />
                                            </div>
                                        )
                                    }
                                })}
                                <div className="PageItem-ColorButton-Options">
                                    {this.props.colors.map((color) => {
                                        return (
                                            <div className="PageItem-ColorButton">
                                                <ColorButton
                                                    colorId={color.colorId}
                                                    colorName={color.colorName}
                                                    colorHex={color.colorHex}
                                                    colorImg={color.colorImg}
                                                    onClick={this.changeColor}
                                                />
                                            </div>)
                                    })}
                                </div>
                                {this.props.colors.map((color) => {
                                    if (color.colorId === this.state.color) {
                                        this.setState.selectedColor = color.colorName;
                                        return (
                                            <div>
                                                <p>{color.colorName}</p>
                                            </div>
                                        )
                                    }
                                })}
                                <div className="PageItem-SizeButton-Options">
                                    {this.props.sizes.map((size) => {
                                        return (
                                            <div className="PageItem-SizeButton">
                                                <SizeButton
                                                    sizeId={size.sizeId}
                                                    sizeValue={size.sizeValue}
                                                    onClick={this.changeSize}
                                                />
                                            </div>)
                                    })}
                                </div>
                            </Col>
                            <Col>
                                <p>{this.props.description}</p>
                            </Col>
                        </Row>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="secondary" onClick={this.handleClose}>
                            Close
          </Button>
                        <Link to={`/products/${this.props.id}`}><Button variant="secondary">See More</Button></Link>
                        <Button variant="primary" onClick={this.addItem}>
                            Add to Cart
          </Button>
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}

export let inCart = [];

export let cartColors = [];

export let cartTotal = 0;


export default PageItem;
import React, { Component } from 'react';
import { Col, Row } from 'react-bootstrap';
import { inCart, cartTotal, cartColors } from '../PageItem/PageItem.js';
import CartItem from '../CartItem/CartItem.js';
import Products from '../../productData.js';
import Navbar from '../../Navbar/Navbar.js';
import Footer from '../../Footer/Footer.js';
import CartImg from '../../Images/SVG/cart2.svg';


class Cart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cartList: inCart,
            finalTotal: cartTotal.toFixed(2)
        }
    }

    removeItem(itemId, itemPrice) {
        var itemIndex = this.state.cartList.indexOf(itemId);
        var newList = inCart.splice(itemIndex, 1);
        var newTotal = (this.state.finalTotal - itemPrice).toFixed(2);
        this.setState({ cartList: newList, finalTotal: newTotal });
    }

    render() {
        console.log(this.state.finalTotal);
        return (
            <div className="Page">
                <Navbar />
                <div className="Cart">
                    <img src={CartImg}></img>
                    <h1>Shopping Cart</h1>
                    <div className="Cart-Items">
                        {Products.map((product) => {
                            var productId = cartColors.find(item => item.item === product.id);
                            if (inCart.includes(product.id)) {
                                return (
                                    <Row middle="xs" className="Cart-CartItem">
                                        <Col xs={6}>
                                            <CartItem
                                                id={product.id}
                                                name={product.name}
                                                img={product.img}
                                                description={product.description}
                                                price={product.price}
                                            /></Col>
                                        <Col xs={6}>
                                            <div className="Cart-CartOptions">
                                                {product.colors.map((color) => {
                                                    if (productId.color === color.colorId) {
                                                        return (
                                                            <div>
                                                                <p>{color.colorName}</p>
                                                            </div>
                                                        )
                                                    }
                                                })}
                                                {product.sizes.map((size) => {
                                                    if (productId.size === size.sizeId) {
                                                        return (
                                                            <div>
                                                                <p>{size.sizeValue}</p>
                                                            </div>
                                                        )
                                                    }
                                                })}
                                                <button onClick={() => this.removeItem(product.id, product.price)}>Remove</button>
                                            </div></Col>
                                    </Row>
                                )
                            }
                        })}
                    </div>
                    <div className="Cart-Total">
                        <h1>{this.state.finalTotal}</h1>
                    </div>
                </div>
                <Footer />
            </div>
        )
    }
}


export default Cart;
import React,{Component}来自'React';
从'react bootstrap'导入{Col,Row};
从“../PageItem/PageItem.js”导入{Invot,cartTotal,cartColors};
从“../CartItem/CartItem.js”导入CartItem;
从“../../productData.js”导入产品;
从“..//Navbar/Navbar.js”导入导航栏;
从“../../Footer/Footer.js”导入页脚;
从“../Images/SVG/cart2.SVG”导入CartImg;
类Cart扩展组件{
建造师(道具){
超级(道具);
此.state={
cartList:Invot,
最后
var newList = inCart.splice(itemIndex, 1);
...
this.setState({ cartList: newList, finalTotal: newTotal });