【问题标题】:Display nested Json array fetched data React native显示嵌套的 Json 数组获取的数据 React native
【发布时间】:2020-03-27 12:03:00
【问题描述】:

所以我是反应原生的新手,我正在尝试显示 Json 获取数据的嵌套元素,但我不知道该怎么做。 在 fetch api 中使用 react hooks 后:

export default function MedProfilScreen({ route }) {
  //const {id,name,specialite,work}=route.params;
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch("http:......")
      .then(response => response.json())
      .then(res => {
        setData(
          res);
        console.log(res);
      })
      .done();
  },[]);
}

我收到了这个回复:

Array [
  Object {
    "code": "12459552",
    "id": 7,
    "name": "Dr xavier vilan",
    "speciality": "Cardio",
  },
  Object {
    "education": Array [
      Object {
        "date_debut": "2020-02-07",
        "date_end": "2020-02-06",
        "diploma": "asmaa",
        "school": "asmaa",
        "city": "vullez",
      },
      ]}
]

所以我想显示例如:姓名:xavier 博士.. 文凭:asmaa

return(
<View>  name: Dr xavier.. diploma: asmaa            </View>
)

有人知道怎么做吗。谢谢

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    我不知道这就是你要找的东西,但我会试试看:

    代码:

    const renderText = () => {
        // as soon as we received the data, we will display it
        if (data.length > 0){
          return (
             <Text> name: {data[0].name} diploma: {data[1].education[0].diploma}</Text>
          )
        }
    }
    return (
      <View>
         {renderText()}
      </View>
    );
    

    输出:

    演示:

    https://snack.expo.io/rkbsDdoU8

    【讨论】:

    • 是的,这就是我需要的,但我只是收到拼写错误:data[0].name is not an object
    • @AymenAymen 我已经更新了我的答案和演示链接
    【解决方案2】:

    由于您已经将回复保存在 data 中,因此您的数据应该是这样的,

    data = [
      {
        code: "12459552",
        id: 7,
        name: "Dr xavier vilan",
        speciality: "Cardio"
      },
      {
        education: [
          {
            date_debut: "2020-02-07",
            date_end: "2020-02-06",
            diploma: "asmaa",
            school: "asmaa",
            city: "vullez"
          }
        ]
      }
    ]
    

    现在您可以访问name & diploma,如下所示,

    name: data[0].name
    diploma: data[1].education[0].diploma
    

    希望这对您有所帮助。如有疑问,请随意

    【讨论】:

    • 感谢您的回复,Tim 上面的回答已解决!
    【解决方案3】:

    试试这个:

    return (
       <View>{JSON.stringify(data, null, 2)}</View>
    )
    

    【讨论】:

    • 它只是在我的应用屏幕上显示了 res 的 consol 日志
    【解决方案4】:

    参考你想要的项目试试这个

    return(
         <View>  
              <Text> name: {data[0].name} diploma: {data[1].education[0].diploma}         
               </Text>
         </View>
    )
    

    【讨论】:

    • 感谢您的回复,Tim 上面的回答已解决!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2022-08-03
    • 1970-01-01
    • 2020-03-09
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多