首页 > 解决方案 > 在 React Native 中显示数据数组中的值

问题描述

我从我的 API 中获取了这些数据。如何在文本输入中显示 name 属性的值?

[
    {
        "id": "1",
        "userid": "",
        "is_admin": "1",
        "name": "Anshul Gupta",
        "email": "testuser@gmail.com",
        "company": "Kissui Metaliks and Steels Pvt. Ltd.",
        "jobtitle": "Director",
        "address": "366 and 368, MIE Part A, Bahadurgarh,Haryana,IndiaBahadurgarh, Haryana",
        "cityid": "haryana",
        "stateid": "Abohar",
        ...
    }
]

标签: arraysreactjsreact-nativefetch

解决方案


我不确定,但我想这就是你要找的:

        import React, { Component } from 'react';
        import { Text, View, TextInput } from 'react-native';

        export default class HelloWorldApp extends Component {

          constructor(props) {
            super(props);
            this.state = { dataSource:[]}
          }

          async componentDidMount(){
            try {
              AsyncStorage.getItem("user")
                .then(async (user)=>{
                  const response = await fetch('myAPi=' + userData.id );
                  const responseJson = await response.json();
                  this.setState({ dataSource: responseJson})
                })
            }
          }

          render() {
            return (
              <View>
                <Text>{this.state.dataSource[0]['name']}</Text>
                <TextInput
                  style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} 
                  onChangeText={text => onChangeText(text)}
                  value={this.state.dataSource[0]['name']}
                />
                <TextInput
                  style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} 
                  onChangeText={text => onChangeText(text)}
                  value={this.state.dataSource[0]['email']}
                />
              </View>
            );
          }
        }

推荐阅读