简体   繁体   English

从 Props 中检索数据数组

[英]Retrieving an Array of Data from Props

I am trying to retrieve an array of data which is in a JSON format, and is passed to a React Component.我正在尝试检索 JSON 格式的数据数组,并传递给 React 组件。 If I use console.log(props), I can see data as follows: { props: {data: [[array]]}}.如果我使用 console.log(props),我可以看到如下数据:{ props: {data: [[array]]}}。

The problem I have is that I am not able to drill down into the actual data.我遇到的问题是我无法深入研究实际数据。 I have tried props.data.map and props.map, and both of theses return undefined.我试过 props.data.map 和 props.map,这两个都返回未定义。

The JSON format is as follows: JSON 格式如下:

someData = {
             data: [
                     [
                       { 'id':'1',
                         'name': 'somename'
                        }
                     ]
                   ]
            }

Is there another object that I need to drill down to get to the data?是否还有另一个 object 我需要深入了解才能获取数据?

The problem here is that the Data is in JSON format and to retrieve and use the the data in JavaScript, you have to parse it into a JavaScript Object. The problem here is that the Data is in JSON format and to retrieve and use the the data in JavaScript, you have to parse it into a JavaScript Object. You can simply do that using the JSON.parse() method to parse it into a object.您可以简单地使用JSON.parse()方法将其解析为 object。 Just pass the prop into this object before sending it and it will work as expected then.只需在发送之前将道具传递到此 object 中,然后它将按预期工作。

data = JSON.parse(data); // if it was defined using let keyword

Then just pass it to the required component.然后只需将其传递给所需的组件。
You can learn more about JSON.parse() from here您可以从此处了解有关JSON.parse()的更多信息

The object structure is layered differently than you were expecting. object 结构的分层方式与您的预期不同。 It is encapsulated within an additional object with another props property, and the inner array is wrapped in another array.它被封装在具有另一个 props 属性的附加 object 中,并且内部数组被包装在另一个数组中。
props.props.data[0].map

 let data = JSON.parse(someData) data.forEach(element => { element.map(item => { return item }) })

if you are exact know there is only one item in array then use somedata.data[0].item;如果您确切知道数组中只有一项,请使用 somedata.data[0].item; but parse json first because json is strigfy when we recieve json但首先解析 json 因为当我们收到 json 时 json 是 stigfy

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

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