gpt4 book ai didi

javascript - 如何从 PHP 后端接收 JSON 对象并将其转换为前端的 JavaScript 数组

转载 作者:行者123 更新时间:2023-11-30 19:06:13 25 4
gpt4 key购买 nike

我有一个 php 后端,它向 React 前端返回一个 json 对象。对象以这种格式到达

{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", …}

等等

我想获取这个对象并获取数据数组,然后循环数组。这是我目前所拥有的:

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;

这会引发错误

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.

如果我将 items[0] 包装在 JSON.stringify 中,我会得到一个字符串,但我想将响应对象转换为一个数组,这样我就可以使用 data.map(item => etc).

更新:

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

最佳答案

这个怎么样?将数组直接传递给状态,而不是传递一个对象。这样您就可以直接遍历数组而不是对象值。

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;

关于javascript - 如何从 PHP 后端接收 JSON 对象并将其转换为前端的 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58962503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com