无法从react-native中的嵌套json获取数据

时间:2019-01-14 09:09:01

标签: image react-native state

我想从嵌套的json中获取数据。

我的json如下所示

    {
    "id": 2,
    "cover_image": "http://13.233.31.123/media/homepage-banner.jpg",
    "name": " Website",
    "tagline": " IT Right",
    "status": "ACTIVE",
    "client_name": "Company",
    "start_date": null,
    "end_date": null,
    "technology_frontend": "HTML, CSS, JAVASCRIPT\r\nCMS: WORDPRESS",
    "technology_backend": "PHP",
    "description": "We provide robust and high quality Custom Web Development.\r\nCodism is a global technology and business services consulting firm. We are specialized in servicing business market needs specializing in Web Design and Development, Online marketing and IT Consulting Services to commercial and government customers. We provide staffing and end-to end consulting services for organizations.",
    "gallery": [
        {
            "project": 2,
            "image": "http://localhost/media/gallery_image/homepage-banner.jpg"
        },
        {
            "project": 2,
            "image": "http://localhost/media/projects/gallery_image/software-development.jpg"
        },
        {
            "project": 2,
            "image": "http://localhost/media/projects/gallery_image/New_FRS_Image_Mobile_app_development.jpg"
        }
    ]
}

我想获取画廊的所有图像。如果我正在做console.log(this.state.gallery[0]),但我正在做console.log(this.state.gallery[0].image)却给出了错误,但我没有怎么做。我在gallery: { images: [] }中找到了使用状态,所以我的状态是这样的。我应该如何使用地图来获取所有详细信息,请帮忙。预先感谢

3 个答案:

答案 0 :(得分:0)

我希望您在setState时出错 您的状态应该是

this.state = { data : {} }

在componentDidMount或任何地方设置状态时,请执行类似的操作

this.setState({ data : jsonData )};

之后,您可以使用渲染方法上的数据来渲染图像。

this.state.data.galley.map(item => <Image source={{item.image}/>);

如果您的jsonData是一个数组,并且您想渲染该数组的第一个对象,请这样做

this.state = {data: []};
this.setState({data:jsonData)};
this.state.data[0].galley.map(item => <Image source={{item.image}/>);

如果您的jsonData是一个数组,并且您想渲染所有嵌套的图像,请这样做。

this.state = {data: []};
this.setState({data:jsonData)};
this.state.data.map(data => data.galley.map(item => <Image source={{item.image}/>));

答案 1 :(得分:0)

如果您想拥有自己州的所有图像,则可以执行以下操作。

使用setState时,可以尝试setState({...yourJson})在您的状态下创建json的新对象。

答案 2 :(得分:0)

尝试先解析JSON

.then((responseData) => {
  newData = JSON.parse(responseData);
  this.setState({ data: newData });
  this.setState({ ... newData.gallery });
})