它无法读取未定义的属性“ id”,但是我有一些值,所以不知道它为什么不知道

时间:2019-10-02 12:50:46

标签: reactjs react-redux

我正在使用 React ContextApi 来管理状态组件。 我的data.js中有一些文件,但拒绝在Details.js页面上显示。

我知道出了点问题,但是它没有显示任何错误代码,也没有显示其文字"Cannot read property 'id' of undefined"

enter image description here

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

const BookContext = React.createContext()
   class BookProvider extends Component {
   state = {
        products: [...storeProducts],
        details: detailProduct
    };

    componentDidMount() {
    this.setProducts();
}

setProducts = () => {
    let products = [];
    storeProducts.forEach(item => {
        const singleItem = {...item};
        products = [...products, singleItem];
    });

    this.setState(() => {
        return {products}
    });
};

handleDetail = () => {
    console.log("Hello from detail")
};
addToCart = () => {
    console.log("Hello from add to cart")
};
render() {
    return (
        <BookContext.Provider value={{
            // products: this.state.products,
            // details: this.state.details,
            // Destructuring all the values that is in the state property
            ...this.state,
            handleDetail: this.handleDetail,
            addToCart: this.addToCart
        }}>
            {this.props.children}
        </BookContext.Provider>
    )
}
};

const BookConsumer = BookContext.Consumer;

export { BookProvider, BookConsumer };

This is the Details.js file on the project
import React, { Component } from 'react';
import { BookConsumer } from '../context';
import { Link } from 'react-router-dom';
import { ButtonContainer } from './Button';

 class Details extends Component {
    render() {
        return (
            <BookConsumer>
                {(value) => {
                    const {id, company, img, price, title, info, inCart} = 
                          value.detailProduct;
                    return (
                        <div className="container py-5">
                            {/* TITLE */}
                            <div className="row">
                            <div className="col-10 mx-auto text-center 
text-slanted text-blue my-5">
                                <h1>{title}</h1>
                            </div>
                            </div>
                        </div>
                    )
                }}
            </BookConsumer>
        );
    }
}

export default Details;

2 个答案:

答案 0 :(得分:1)

似乎value参数没有设置属性detailProduct。先检查一下。

答案 1 :(得分:1)

您正在破坏value.detailProduct而不是value.details

实际上context.js

value={{
            ...this.state,
            handleDetail: this.handleDetail,
            addToCart: this.addToCart
        }}

并且state没有detailProduct键。