javascript - 如何使用 React JS 从 JSON 文件中获取嵌套对象

标签 javascript arrays json reactjs object

我如何从 reactjs 中的 json 文件中获取嵌套对象,我如何能够获取第一组对象,但我无法获取嵌套对象。

ID - {this.props.product.id}//输出 - 1(工作正常)

嵌套细节 - {this.props.product[detailPage]}//给出错误

代码:

export default class Products extends React.Component {
    constructor() {
        super();
        this.state = {
            "productdetails": false
        }
    }
    /*componentWillMount() {
        let url = "./products.json";
        Request.get(url)
            .then((res) => {
                this.setState({
                    data: res.body.data
                });
            })
            .catch(function (err) {
                alert(err);
            });
    }*/
    handleinputdata() {
        alert();
    }
    render() {
        var productdetails = this.state.productdetails;
        if (productdetails == false) {
            //var status = (<ProductsC onUserInputs={this.handleinputdata.bind(this)} />);
            var status = (<ProductsDetailComponent onUserInputs={this.handleinputdata.bind(this)} />);
        } else {
            var status = (<ProductsDetailComponent onUserInputs={this.handleinputdata.bind(this)} />);
        }
        return (
            <Grid>
                <Row>
                    <Col sm={12} className="text-center">
                        <h2>MEN'S STYLES</h2>
                        <p>To Make a Lasting Impression</p>
                    </Col>
                </Row>

                {status}

                {/*<Route path="/products" exact component={ProductsC} />*/}
                {/*<Route path="/products/:id" component={ProductDetail} />*/}
            </Grid>
        );
    }
}

ID  - {this.props.product.id} // output - 1 (works fine)

Nested details - {this.props.product[detailPage]} // gives Error

/* Products Detail Page Component starts */
class ProductsDetailComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
    }
    componentWillMount() {
        let url = "./products.json";
        var jsonParse = JSON.stringify(this.state.data);


        console.log(jsonParse);

        Request.get(url)
            .then((res) => {
                this.setState(
                    {
                        data: res.body.data

                    }
                );

                console.log('url - ' + url);
                console.log('res - ' + res.body.data);

            })
            .catch(function (err) {
                alert(err);
            });

    }
    render() {
        return (
            <Row className="products-container">
                <Col sm={12}>

                    {JSON.stringify(this.state.data[0])}
                    {
                        this.state.data.map(
                            (product, index) => (
                                <ProductDetailData key={index} product={product} />
                            )
                        )
                    }
                </Col>
            </Row>
        )
    }
}
/* Products Component ends */


// Products Starts
class ProductDetailData extends React.Component {
    handleClick() {
        //console.error('Id'+this.refs.idInputText.value);
        const { title, img, des, rs, buy, details } = this.props.product;
        this.props.onUserInputs(title, img);
    }

    render() {

        const { title, img, des, rs, buy, details } = this.props.product;

        return (
            <Col xs={12} sm={3} className="text-center product-list">
                <Card>
                    <CardImg src={img} alt="product img" />

                    ID  - {this.props.product.id} <br/>
                    img - {this.props.product.img} <br/>
                    title - {this.props.product.title} <br/>
                    des - {this.props.product.des} <br/>
                    rs - {this.props.product.rs} <br/>
                    buy - {this.props.product.buy} <br/>
                    details - {this.props.product.details} <br/>

                    {/*details - {this.props.product[detailPage]} <br/>*/}



                    <Link to="/">
                        <CardTitle>{title}</CardTitle>
                    </Link>
                    <CardText>{des}</CardText>
                    <CardText>Rs : {rs} /-</CardText>

                    <Button className='btn btn-danger'>{buy}</Button> &nbsp;
                    {/*<Button className='btn btn-primary'></Button>*/}
                    <Button onClick={this.handleClick.bind(this)} className="btn btn-primary">
                        {details}
                    </Button>
                </Card>
            </Col>
        )
    }
}

enter image description here

不确定我在这里遗漏了什么,只使用 reactjs。 每当我尝试单击产品页面时,我都会尝试显示产品详细信息页面,并且仅尝试显示单个产品数据。

我的 JSON 代码:

{
    "data": [
        {
            "id": 1,
            "title": "Jackets",
            "img": "./img/p1.jpg",
            "des": "Pure Leather Jacket",
            "rs": 9000,
            "buy": "Add to Cart",
            "details": "View Details",
            "detailPage": [
                {
                    "productDetail": "Made of Pure Leather",
                    "qty": 4,
                    "size": "S, M, L, XL, XXL",
                    "color":"white, black",
                    "AddtoCart" : "Add to Cart"
                }
            ]
        }
    ]
}

最佳答案

试试下面的代码。

/* Products Detail Page Component starts */
class ProductsDetailComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
    }
    componentWillMount() {
        let url = "./products.json";
        var jsonParse = JSON.stringify(this.state.data);


        console.log(jsonParse);

        Request.get(url)
            .then((res) => {
                this.setState(
                    {
                        data: res.body.data

                    }
                );

                console.log('url - ' + url);
                console.log('res - ' + res.body.data);

            })
            .catch(function (err) {
                alert(err);
            });

    }
    render() {
        return (
            <Row className="products-container">
                <Col sm={12}>

                    {JSON.stringify(this.state.data[0])}
                    {
                        this.state.data.map(
                            (product, index) => (
                                <ProductDetailData key={index} product={product} productDetails={product.detailPage} />
                            )
                        )
                    }
                </Col>
            </Row>
        )
    }
}
/* Products Component ends */


    //specify right path where this component is located
import ProductsDetailChildren from './ProductsDetailChildren';
// Products Starts
class ProductDetailData extends React.Component {
    constructor() {
        super();
        this.state = {
            data: []
        }
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        //console.error('Id'+this.refs.idInputText.value);
        const { title, img, des, rs, buy, details } = this.props.product;
        this.props.onUserInputs(title, img);
    }

    render() {

        const { product, productDetails } = this.props;

        let rows = []; 
        if(this.props.productDetails){ 
            if(this.props.productDetails.length > 0){ 
                this.props.productDetails.forEach((data, i) => { 
                    rows.push(<ProductsDetailChildren key={i} qty={data.qty} productDetail={data.productDetail} size{data.size} color={data.color} AddtoCart={data.AddtoCart} />) 
                }) 
            }
        }

        return (
            <Col xs={12} sm={3} className="text-center product-list">
                <Card>
                    <CardImg src={this.props.product.img} alt="product img" />


                    ID  - {this.props.product.id} <br/>
                    img - {this.props.product.img} <br/>
                    title - {this.props.product.title} <br/>
                    des - {this.props.product.des} <br/>
                    rs - {this.props.product.rs} <br/>
                    buy - {this.props.product.buy} <br/>
                    details - {this.props.product.details} <br/>

                    {/*details - {this.props.product[detailPage]} <br/>*/}

                    product details - {rows}

                    <Link to="/">
                        <CardTitle>{this.props.product.title}</CardTitle>
                    </Link>
                    <CardText>{this.props.product.des}</CardText>
                    <CardText>Rs : {this.props.product.rs} /-</CardText>

                    <Button className='btn btn-danger'>{this.props.product.buy}</Button> &nbsp;
                    {/*<Button className='btn btn-primary'></Button>*/}
                    <Button onClick={this.handleClick} className="btn btn-primary">
                        {this.props.product.details}
                    </Button>
                </Card>
            </Col>
        )
    }
}


class ProductsDetailChildren extends React.Component { 
constructor(props) { 
super(props); 
this.state = { 

} 
} 
render() { 

const { qty, productDetail, size, color, AddtoCart } = this.props; 

return ( 
    <div>
        <ul>
            <li>Quantity: {qty}</li>
            <li>productDetail: {productDetail}</li>
            <li>size: {size}</li>
            <li>color: {color}</li>
            <li>AddtoCart: {AddtoCart}</li>
        <ul>
    </div>
) 
} 
}

关于javascript - 如何使用 React JS 从 JSON 文件中获取嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519248/

相关文章:

javascript - Webpack:是否有一个加载器只忽略 require() 调用?

javascript - 向上取整 0.10

javascript - Next JS npm start app load 404 page not found 物理页面错误

arrays - 数组中的条件和

json - 如何在 swift4 中使用数组将 json 数据显示到 tableview 中?

python - 使用多边形坐标将带注释的图像转换为二进制掩模图像

javascript - 给定 X、Y、宽度和高度变量,如何在 Google App 脚本中查找形状的开始值和结束值?

javascript - 如何将 id 添加到 .before 函数中的段落元素?

arrays - NumPy:用三维数组中的平均值替换第三维的所有元素

javascript - 将 JavaScript 对象/映射转换为嵌套数组?