繁体   English   中英

在reactJS上获取单个JSON数据

[英]Fetching individual JSON data on reactJS

当我从服务器解析JSON到我的React前端时,它工作得很好,但是当我添加参数以显示单个项目时,我得到了一个错误。 如何在React JS上显示单个JSON数据。 我从其余服务器获取JSON数据。 我的代码如下所示。

为了获取JSON,我使用以下方法。

state = {
    isLoading: true,
    groups: [],
};  

async componentDidMount() {
    const response = await fetch('/product/all/1');
    const body = await response.json();
    this.setState({ groups: body, isLoading: false });
}

这就是我所说的数组

  {this.state.groups.map(group => <div className="col-sm-12 col-md-6 col-lg-4 p-b-50">
                                    {/* Block2 */}
                                    <div className="block2">
                                        <div className="block2-img wrap-pic-w of-hidden pos-relative block2-labelnew">
                                             <img src={group.thumbnail} />
                                            <div className="block2-overlay trans-0-4">
                                                <a href="#" className="block2-btn-addwishlist hov-pointer trans-0-4">
                                                    <i className="icon-wishlist icon_heart_alt" aria-hidden="true" />
                                                    <i className="icon-wishlist icon_heart dis-none" aria-hidden="true" />
                                                </a>
                                                 <button key={group.id} onClick={() => this.add(group.productid, group.name)} className="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">Add to Cart</button>

                                            </div>
                                        </div>

                                        <div className="block2-txt p-t-20">

                                             <a  href={`/productdetails/` + group.productid}>{group.name}</a>

                                        </div>
                                    </div>
                                </div>)}

我收到一条错误消息:“ TypeError:this.state.groups.map不是函数

我的Spring后端,用于调用所有项目和单个项目,如下所示

@GetMapping("/product")
public List<Product> index(){
    return productRepository.findAll( );
}

@GetMapping("/product/all/{id}")
public Product show(@PathVariable String id){
    int productId = Integer.parseInt(id);
    return productRepository.findOne(productId);
}

PS两种api在邮递员上进行测试时似乎都可以正常工作,并且提取(“ api / products”)也可以正常工作

this.state.groups.map is not a function 这意味着React期望this.state.groups是一个数组。 如果您只退货一项,请按照以下步骤进行:

this.setState({ groups: [body], isLoading: false });

这样,body将成为数组中的第一个也是唯一的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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