【问题标题】:Fetching individual JSON data on reactJS在 reactJS 上获取单个 JSON 数据
【发布时间】:2019-09-03 05:00:59
【问题描述】:

当我从我的服务器解析一个 JSON 到我的反应前端时,它工作得很好,但是当我添加一个参数来显示单个项目时,我得到一个错误。如何在 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 is not a function

我的 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);
}

P.S 在邮递员上测试时,两个 api 似乎都可以正常工作,并且获取(“api/products”)也可以正常工作

【问题讨论】:

  • /product/all/{id} API 将返回单个对象 (.findOne)

标签: json spring reactjs rest


【解决方案1】:

this.state.groups.map is not a function 。这意味着 React 期望 this.state.groups 是一个数组。如果您只退回一件商品,请这样做:

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

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

【讨论】:

    猜你喜欢
    • 2022-12-22
    • 2021-05-22
    • 2014-06-19
    • 1970-01-01
    • 2017-01-03
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多