简体   繁体   中英

in react when using state in a default component class it gives undefined

in this react code when I try to access this.state it says it is undefined. I have tried scoping and still the error comes. I want to access this.state.cartItems property to make it add to cart. but it doesn't let me access the property of this.state. It is undefined.

I want to access this.state in below function.

 addToCart(product) {
            console.log(this.state.products)
            console.log('adding to cart ...')
        }


import React, { Component } from "react";
import Product from "./../components/client/Product";
import Cart from "./../components/client/Cart";
import data from "./../data.json";

export default class StorePortal extends Component {
    constructor() {
        super();    
    }
    state = {
        products: data.products,
        cartItems: []
    };
    addToCart(product) {
        console.log(this.state.products)
        //let items = this.state.cartItems.slice();
        // let isAdded = false;
        // items.forEach((item)=>{
        //     if(item._id === product._id){
        //         item.count++;
        //         isAdded = true;
        //     } 
        //     if(!isAdded){
        //         items.push({...product, count: 1});
        //     }
        // })

        console.log('adding to cart ...')
    }
    removeFromCart(product) {
        console.log('removing from cart')
    }

    render() {

        return (
            <div>
                <div className="content">
                    <div className="main">
                        <Product
                            products={this.state.products}
                            addToCart={this.addToCart}
                            removeFromCart={this.removeFromCart}
                        ></Product>
                    </div>
                    <div className="sidebar">
                        <Cart cartItems={this.state.cartItems} />
                    </div>
                </div>
            </div>
        );
    }
 
}

If I understand what you're asking, the problem is that you're doing this: addToCart={this.addToCart} on the Product component.

The short answer: change it to an inline arrow function:

addToCart={(...args) => this.addToCart(...args)}

The problem with passing the function directly is that you lose the scope; this no longer points to the component instance. Generally speaking, a function's scope--what this points to--is bound to the object it was invoked on:

// inside someMethod, "this" will be myObject.
myObject.someMethod()

 // invoked independently, "this" is no longer myObject.
const { someMethod } = myObject;
someMethod();

Put state in constructor.

 constructor(props) {
        super(props);  
       this.state = {
        products: data.products,
        cartItems: []
    }
} 

Then trying accessing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM