简体   繁体   中英

How do I receive a JSON object from PHP backend and convert to JavaScript array for frontend

I have a backend in php that is returning a json object to a React frontend. The object arrives in this format

{data: Array(401), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
 config: {url: "http://localhost/index.php", method: "post", headers: {…}, transformRequest: 
 Array(1), transformResponse: Array(1), …}
 data: Array(401)
 [0 … 99]
  0: {id: "191", name: "Thunder", description: null, created: "2012-10-04 12:36:29", slug: "thunder", …}
  1: {id: "95", name: "Break", description: null, created: "2010-03-26 13:19:11", slug: "break", …}

etc.

I want to take this object and grab the data array and then loop the array. This is what I have so far:

import React from 'react';
import axios from 'axios';

class Container extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
   }

   componentDidMount() {
   axios({
      method: 'post',
      url: 'http://localhost/index.php',
      timeout: 4000,          
    })
    .then(response => {
      this.setState({data:response})
    })

    .catch(error => console.error('timeout exceeded'))

  }

   render() {
    const {data} = this.state;
    const items = Object.values(data).map(function(num) {
      return num
    });        
      return (
          <div>
            {items}
          </div>
      )
  }

}

export default Container;

This throws an error of

Uncaught Error: Objects are not valid as a React child (found: object with keys {id, name, description, created, slug, image, tags}). If you meant to render a collection of children, use an array instead.

If I wrap the items[0] in JSON.stringify I get a string, but I want to convert the response object to an array so I can use data.map(item => etc) .

Update:

num = num = (401) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}  
[0 … 99]
0: {id: "191", name: "Thunder", description: null, created: "2012-10-04 12:36:29", slug: "thunder", …}
1: {id: "95", name: "Break", description: null, created: "2010-03-26 13:19:11", slug: "break", …} etc etc

How about this? Pass the array directly to the state instead of passing an object. This way you can loop directly through the array instead of the object values.

import React from 'react';
    import axios from 'axios';

    class Container extends React.Component{
      constructor(props) {
        super(props);
        this.state = {
          data: [],
        };
       }

       componentDidMount() {
       axios({
          method: 'post',
          url: 'http://localhost/index.php',
          timeout: 4000,          
        })
        .then(response => {
          this.setState({data:response.data})
        })

        .catch(error => console.error('timeout exceeded'))

      }

       render() {
        const {data} = this.state;
        const items = data.map(function(num) {
          return num.id;
        });        
          return (
              <div>
                {items}
              </div>
          )
      }

    }

    export default Container;

ok so with some of the answers and a little more experimenting this is what I have and its a start to the rest of the solution

I changed this line

 this.setState({data:response})

to

 this.setState({data:response.data})

and changed the render to this

  render() {
    const {data} = this.state
    let result = [];
    Object.values(data).map(num =>
      result.push(num)
     );
    return (
          <div>
            {result.map(tile => 
             `<div><img src='${tile.image}'/></div>` 
              )}
          </div>
      )
  }

Use .setState() . It will make react re-render the page. Also, what's the value of num in your function? Might want to check that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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