如何在React Native中映射对象?

问题描述 投票:0回答:2

我需要一些帮助,在jsx里面的json中生成json in react native ..我从服务器获得的响应是​​对象所以我如何循环它们?我从服务器得到一个有效的响应,但我得到的问题是map方法,因为我认为map方法只适用于数组。所以请帮我做这个。以下是json对象

JSON

    {
    "content": "<p><strong>Preliminary Exam; MCQ –1</strong></p>\n",
    "meta": {
        "access": 1,
        "status": 0,
        "progress": 0,
        "marks": 0,
        "max": 60,
        "questions": [

            {
                "type": "single",
                "hint": "",
                "explanation": "",
                "content": "<p>Question Statement :</p>\n<ol>\n<li>The is question:</li>\n</ol>\n",
                "options": [
                    "(a).Answer1",
                    "(b).Answer2 ",
                    "(c).Answer3 ",
                    "(d).Answer4 "
                ],
                "correct": "4",
                "marks": 4,
                "user_marks": 0,
                "status": 0,
                "marked": null,
                "auto": 1
            },
            {
                "type": "single",
                "hint": "",
                "explanation": "",
                "content": "<p>2.Question 2</p>\n",
                "options": [
                    "(a) one ",
                    "(b) two  ",
                    "(c) three ",
                    "(d) four"
                ],
                "correct": "2",
                "marks": 4,
                "user_marks": 0,
                "status": 0,
                "marked": null,
                "auto": 1
            }
        ]
    }
}

我尝试过如下

示例代码

state = { details: [] };

componentWillMount() {
   AsyncStorage.getItem('userdetail').then((value) => {
       console.log(value);

       fetch('https://www.mywebsite.com', {
            method:'GET',
            headers: {
                'Authorization': value
            }
        })
        .then((response) => response.json())
        .then((responseData) =>
             this.setState({
                 details:responseData.meta.questions
             })
        );

    });
}

render() {
    console.log(this.state);
    return (
        this.state.details.map( a =>
            <Card>
                <CardSection>
                    <Text>{a.questions.content}</Text>
                </CardSection>
            </Card>     
    );
} 

但得到错误this.state.details.map不是一个功能?我的渲染方法有问题吗?请帮忙。

json react-native rendering jsx
2个回答
1
投票

问题是responseData,它是一个对象而不是数组,试试用

details:responseData.meta.questions

0
投票

map方法/函数的问题在于你是在单个对象而不是数组中使用它。你的responseData是一个巨大的物体,里面有questions阵列。您可以通过以下问题进行映射:

render() {
    console.log(this.state);
    return (
        this.state.details.meta.questions.map( a =>
            <Card>
                <CardSection>
                    <Text>{a.content}</Text>
                </CardSection>
            </Card>

        );
     );
} 

这应该可以解决您的问题

© www.soinside.com 2019 - 2024. All rights reserved.