简体   繁体   English

如何从 PHP 后端接收 JSON object 并将前端转换为 Z686155AF75A60A0F6E9D80E1 数组

[英]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.我在 php 中有一个后端,它将 json object 返回到 React 前端。 The object arrives in this format object 以这种格式到达

{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.我想拿这个 object 抓取数据数组然后循环数组。 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}).未捕获的错误:对象作为 React 子项无效(发现:object 键为 {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) .如果我将 items[0] 包装在 JSON.stringify 中,我会得到一个字符串,但我想将响应 object 转换为数组,以便我可以使用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.将数组直接传递给 state,而不是传递 object。 This way you can loop directly through the array instead of the object values.这样,您可以直接循环遍历数组而不是 object 值。

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好的,所以有了一些答案和更多的实验,这就是我所拥有的,它是解决方案 rest 的开始

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() .使用.setState() It will make react re-render the page.它会使反应重新渲染页面。 Also, what's the value of num in your function?另外,您的 function 中的num值是多少? Might want to check that可能想检查一下

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

相关问题 如何将多维JSON对象转换为JavaScript数组 - How do I convert a multi dimensional JSON object into javascript array 如何将JSON从PHP转换为Javascript数组 - How can I convert this JSON from PHP to a Javascript array 如何在JavaScript中将JSON从文件转换为数组? - How do I convert JSON from a file into an array in JavaScript? 如何将 javascript 对象文字从 Node 后端发送到浏览器前端? - How to send javascript object literals from a Node backend to the browser frontend? 如何将对象从PHP转换为Javascript中的数组? - How to convert an object from PHP to an Array in Javascript? 如何在JavaScript中将此对象转换为数组? - How do I convert this object to an array in JavaScript? NodeJs:如何从我的 HTML 前端访问我的 JavaScript 后端的功能? - NodeJs: How do I access the functions of my JavaScript backend from my HTML frontend? 如何在 javascript 前端使用 async await 从 async await node.js 后端接收数据 - how to use async await on javascript frontend to receive data from async await node.js backend 如何将文本字段输入从前端发送到后端 - how do I send a text field input from the frontend to the backend 如何从后端获取数据到前端? - How do i fetch data from the backend to the frontend?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM