获取一个 JSON 对象并使用它 reactjs

我对 JS 和 ReactJS 非常陌生,我尝试获取一个端点,它为我提供了一个 JSON 对象,如下所示:


{"IDPRODUCT":4317892,"DESCRIPTION":"Some product of the store"}

我通过这个端点得到这个 JSON 对象:


http://localhost:3000/product/4317892

但是我不知道如何在我的反应应用程序中使用它,我想使用这些数据将它们显示在页面上


我当前的代码看起来像这样,但它不起作用,而且我肯定也不好:


import React, {Component} from 'react';


class Products extends Component {


    constructor(props){

        super(props);

        this.state = {

            posts: {}

        };

    };


    componentWillMount() {

        fetch('http://localhost:3000/product/4317892')

            .then(res => res.json())

            .then(res => {

                this.setState({

                    res

                })

            })

            .catch((error => {

                console.error(error);

            }));

    }


    render() {

        console.log(this.state)

        const { postItems } = this.state;

        return (

            <div>

                {postItems}

            </div>

        );

    }

}


export default Products;

在 console.log(this.state) 中有数据,但我现在很困惑,不知道该怎么办


既然我在这里,我还有一个问题,我想在我的 App.js 中有一个输入,用户可以在其中输入产品的 id 并获得一个,我该如何做到这一点?将数据从 App.js 传递到 Products.js,后者将获取数据并显示它们


浮云间
浏览 171回答 2
2回答

收到一只叮咚

您的状态没有postItems被考虑undefined和反应的属性,因此不会呈现。在您的情况下,无需定义 newconst并直接使用状态。此外,当您setState(),您需要告诉它应该将值设置为哪个状态属性。componentWillMount() {&nbsp; &nbsp; fetch('http://localhost:3000/product/4317892')&nbsp; &nbsp; &nbsp; &nbsp; .then(res => res.json())&nbsp; &nbsp; &nbsp; &nbsp; .then(res => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...this.state, // Not required but just a heads up on using mutation&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; posts: res&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .catch((error => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.error(error);&nbsp; &nbsp; &nbsp; &nbsp; }));}render() {&nbsp; &nbsp; console.log(this.state)&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p><strong>Id: {this.state.posts.IDPRODUCT}</strong></p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>Description: {this.state.posts.DESCRIPTION}</p>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );}

摇曳的蔷薇

我在你的 js 中有 3 个相同的名称:posts、postItems 和 res。React 无法为您确定posts = postItems = res。所以做这样的改变:——this.state = {&nbsp; &nbsp; postItems: {}};——this.setState({&nbsp; &nbsp; postItems: res});——return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {JSON.stringify(postItems)}&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>{postItems.IDPRODUCT}</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>{postItems.DESCRIPTION}</span>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript