首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当导航离开时,反应状态将恢复为以前的状态

当导航离开时,反应状态将恢复为以前的状态
EN

Stack Overflow用户
提问于 2020-05-11 05:41:02
回答 1查看 37关注 0票数 1

我目前正在构建一个React eCommerce应用程序,我在获取真正的购物车总数时遇到了麻烦。

当项目添加到购物车中时,将在项目上找到购物车合计:

代码语言:javascript
复制
 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;

然后,在购物车中,我有以下内容:

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
var newTotal = (cartTotal - itemPrice).toFixed(2);

并使用

代码语言:javascript
复制
this.setState({ cartList: newList, finalTotal: newTotal });

但这提供了一个总的结果。就像它会正确添加一样,但是一旦我开始删除项目,它就会变得很时髦。它将删除项目并在第一次正确更新价格,但在第二次删除时,总数将恢复为完整的前一个总数,并从中删除价格-因此它是关闭的。

我如何才能让总数永久更新?

以下是完整的组件:

PageItem组件:

代码语言:javascript
复制
//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;

购物车组件:

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-11 06:08:22

每次您离开购物车时,您的组件可能会卸载(如果看不到路线以及如何渲染某些组件,则很难确定),因此当组件重新安装时,它会将finalTotal重新初始化为您导入的cartTotal变量。您的removeItem函数只是更改Cart组件的状态变量,而不是导入的cartTotal变量,因此当您导航回购物车时,它会将值设置为cartTotal,该值保存变量的旧值,而不是由removeItem更改的值。确保在使用PageItem组件中的更新程序函数或类似功能将此变量设置为状态之前更新此变量:

代码语言:javascript
复制
import { inCart, cartTotal, updateTotal, cartColors } from '../PageItem/PageItem.js';

...

    removeItem(itemId, itemPrice) {
        var itemIndex = this.state.cartList.indexOf(itemId);
        var newList = inCart.splice(itemIndex, 1);
        var newTotal = (this.state.finalTotal - itemPrice).toFixed(2);
        updateTotal(newTotal); // this will update the cartTotal variable in the PageItem component
        this.setState({ cartList: newList, finalTotal: newTotal });
    }

PageItem

代码语言:javascript
复制
    updateTotal(total) {
        cartTotal = total; // so the total change will persist when you navigate away
    }

或者,您可以将removeItem函数移动到PageItem组件和addItem函数一起,直接修改inCart并直接更新cartTotal

此外,Array.prototype.slice就地修改了一个数组,并返回一个包含已删除元素的数组,所以我不知道您要对这些行做什么:

代码语言:javascript
复制
var newList = inCart.splice(itemIndex, 1);
...
this.setState({ cartList: newList, finalTotal: newTotal });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61719120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档