阅读BD React和Node JS

时间:2019-11-07 22:30:13

标签: reactjs mongodb

我无法在视图中显示数据...我读了一个mongodb地图集,但未找到SetState ...怎么了?

我的代码:

import React, { Component } from 'react';
import {storeProducts, detailProduct} from './data';
import controller from './controller/ApiController';

function createData (item, idArray){

    return{
        id:idArray,
        title: item.title,
        img: item.img,
        price: item.price,
        company: item.company,
        info: item.info,
        inCart: item.inCart,
        count: item.count,
        total: item.total    
    };
}

const ProductContext = React.createContext();
class ProductProvider extends Component {
state = {
    products: [],
    detailProduct: detailProduct,
    cart:[],
    modalOpen:false,
    modalProduct:detailProduct,
    cartSubtotal:0,
    cartTax : 0,
    cartTotal: 0,
    data:[]
}



componentDidMount(){

    this.setProducts();
}


getItem = id =>{


    const product = this.state.products.find(item => item.id  === id);
    return product;

}

handleDetail = id => {
    const product = this.getItem(id);
    this.setState(()=>{

        return {detailProduct : product};
    }

    )
}
addToCart = (id) => {

        let tempProducts = [...this.state.products];
        const index = tempProducts.indexOf(this.getItem(id));
        const product = tempProducts[index];
        product.inCart = true;
        product.count = 1;
        const price = product.price;
        product.total = price;
this.setState(() => {

    return{products:tempProducts, cart:[...this.state.cart,product]};
},()=>{

    this.addTotals();
})
}



okBusqueda(newData) { 
    //console.log("data",newData);
    var i,newArray = []; 
    for (i = 0; i < newData.length; i++) 
    { 
        newArray.push(createData(newData[i],i)); 

    } 

     //Here this.state.data contains information, but not insert 
     //in setState

     console.log(this.state.data);

     this.setState({data: newArray}); 


}

setProducts = () =>{
    let tempProducts = [];

    controller.getProductos(this.okBusqueda.bind(this));

    //this.state.data ---> IS NULL......

    let productosBD = this.state.data;

    console.log("productos", productosBD);

    productosBD.forEach(item =>{

        const singleItem = {...item};
        tempProducts = [...tempProducts,singleItem];

    })

    this.setState(() =>{

        return {products:tempProducts}
    }
    )
}

openModal = id =>{

    const product = this.getItem(id);
    this.setState(()=>{

            return {modalProduct:product,modalOpen:true};

    }
    )
}


closeModal = () =>{

    this.setState(()=>{

            return {modalOpen:false};

    }
    )
}


increment = (id) =>{


    let tempCart = [...this.state.cart];
    const selectedProduct = tempCart.find(item => item.id === id);
    const index = tempCart.indexOf(selectedProduct);
    const product = tempCart[index];

    product.count = product.count + 1;
    product.total = product.count * product.price;

    this.setState(()=>{

        return{

            cart:[...tempCart]
        }

    },()=>{

        this.addTotals();

    })



}

decrement = (id) =>{

    let tempCart = [...this.state.cart];
    const selectedProduct = tempCart.find(item => item.id === id);
    const index = tempCart.indexOf(selectedProduct);
    const product = tempCart[index];

    product.count = product.count - 1;

if(product.count===0){

    this.removeItem(id);


}else{

    product.total = product.count * product.price;

    this.setState(()=>{

        return{

            cart:[...tempCart]
        }

    },()=>{

        this.addTotals();

    })
}



}

removeItem = (id) =>{

    let tempProducts = [...this.state.products];
    let tempCart = [...this.state.cart];
    tempCart = tempCart.filter(item => item.id !== id);
    const index = tempProducts.indexOf(this.getItem(id));
    let removeProduct = tempProducts[index];
    removeProduct.inCart = false;  
    removeProduct.count = 0; 
    removeProduct.total = 0;

    this.setState(()=>{

        return{

            cart:[...tempCart],
            products:[...tempProducts]


        }

    },()=>{

        this.addTotals();

    })

}

clearCart = (id) =>{

    this.setState(()=>{
        return{cart:[]}
    },()=>{

        this.setProducts();
        this.addTotals();
    })

}

addTotals = () =>{

    let subTotal = 0;
    this.state.cart.map(item => (subTotal+=item.total));
    const tempTax = subTotal * 0.1;
    const tax = parseFloat(tempTax.toFixed(2));
    const total = subTotal + tax;
    this.setState(()=>{
        return{
            cartSubtotal:subTotal,
            cartTax:tax,
            cartTotal:total
        }
    })
}

    render() {
        return (
            <ProductContext.Provider value={{
            ...this.state,
            handleDetail:this.handleDetail,
            addToCart:this.addToCart,
            openModal:this.openModal,
            closeModal:this.closeModal,
            increment:this.increment,
            decrement: this.decrement,
            removeItem: this.removeItem,
            clearCart: this.clearCart,
            }}>
             {this.props.children}   
            </ProductContext.Provider>
        );
    }

}
export default ProductProvider;
const ProductConsumer = ProductContext.Consumer;
export {ProductProvider,ProductConsumer};



import {Component} from 'react';


const url ="http://localhost:8080/apiAgenda/"; 
const urlGetProductos='/leerProductos'; 
const urlGetProductosById='leerProductos/idBusqueda'; 
const urlInsertProductos='/insertProducto/Producto'; 
const urlUpdateProductos='/updateProducto/Producto'; 
const urlDeleteProductos='/deleteProducto/Producto';

class ApiController extends Component {

    getProductos(okBusqueda)
    {
        const endpoint = `${url}${urlGetProductos}`;
        //console.log("Buscando")
    fetch(endpoint).then ((response) => 
    {
            //console.log("response",response);
            return response.json();
            }).then (responseData => {
                //console.log(responseData);

                //console.log("Recibi datos");
                okBusqueda(responseData);




        });
    }
}

export default new ApiController();

Null Data Image

0 个答案:

没有答案