how to render a JSON in reactJS

Asked

Viewed 397 times

0

am starting to learn React and want to connect with a server nodejs he’s returning a JSON [{nome:"joão",sobre:"victor"}]

then in React:

class Page extends React.Component{
    constructor(props){
        super(props)     
        Axios.get("/teste").then((response)=>{
            this.resposta=response;
            this.string=this.resposta.data[0].nome
            console.log(this.string)
        })

    }

but I can’t render either Return or string, it only appears on the console.log

1 answer

0


Good afternoon, Joao,

I believe the error is in the statement of function. If I’m not mistaken, Voce can’t create the procedure in the constructor.

You must use the default function of React componentDidMount() or componentWillMount().

That should work:

class Page extends React.Component{
    constructor(props){
        super(props)
    }

    componentDidMount() {
        Axios
            .get("/teste/")
            .then((response) => {
                this.resposta=response;
                console.log(this.resposta)
                this.string=this.resposta.data[0].nome
                console.log(this.string)
            })
            .catch(e => console.log(e))
    }

    render() {
        return (
            <div>

            </div>
        );
    }
}

What I have done: I changed the identation of the Axios procedure to facilitate understanding; I put the search procedure in the function componentDidMount(), which is automatically executed right after the page render; I created 3 console.log, one that returns the answer, another that returns the string and another that returns the error. If you do not receive this.reply on the console, you will know that the error is happening before you get to that part, if you receive this.reply and do not receive this.string, the error is between these two lines, then come back here to help you. If there is any error in the connection, Axios does what is on .catch. In this case, show the error on the console, then Voce can read and see if you can find the error, or put it here for us.

The content of your page will be among the Ivs that exist in the render.

I’m pretty sure the error was the procedure’s position.

Test there and answer here if it worked.

Good luck!

  • it worked to appear on the console,but does not appear on the page

  • I’m trying to get the string to render,

  • @joão.victor_a. how is the render syntax? It would be right to have "{this.string}" (without quotation marks). If it doesn’t work, what I would do is store the name in a state "name". Try this and tell us if it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.