React native 无法从react native中的数组中获取单个对象数据

React native 无法从react native中的数组中获取单个对象数据,react-native,React Native,我是react native的新手。我无法从我的API获取“当前”数据,并且我收到一个错误“无法读取当前属性”,因此我只想获取我的API响应。这是我的API数据,请检查我的代码 { "message": "present in this month", "data": [ { "present": 10 } ], "status": "1" } async componentDidMount() { try {

我是react native的新手。我无法从我的API获取“当前”数据,并且我收到一个错误“无法读取当前属性”,因此我只想获取我的API响应。这是我的API数据,请检查我的代码

{
 "message": "present in this month",
  "data": [
    {
        "present": 10
    }
   ],
  "status": "1"
 }


  async componentDidMount() { 
 try {
            const DEMO_TOKEN = await AsyncStorage.getItem('isLoggedIn');
            if (DEMO_TOKEN != null) {
                console.log('Token', DEMO_TOKEN);
                fetch('http://104.197.28.169:3000/userPresentInThisMonth', {
                    method: 'GET',
                    headers: {
                        Authorization: 'Bearer ' + DEMO_TOKEN,
                    },                     
                })
                    .then(response => response.json())                     
                    .then(responseJson => {
                          alert(responseJson)              
                        console.log(responseJson);
                        this.setState({
                            presentmonthdata : responseJson,
                        });
                    });
            }
        } catch (error) {
            alert(JSON.stringify(error));
            console.error(error);
        }
   }
这是我的文本值

   {this.state.presentmonthdata.data[0] &&
    <Text   style={{color: 'grey',fontSize: 30,   fontWeight: 'bold',  }}>
                            {this.state.presentmonthdata.data[0].present}
                  </Text>
{this.state.presentmonthdata.data[0]&&
{this.state.presentmonthdata.data[0].present}
}解决方案是

{this.state.presentmonthdata.data[0]}
请尝试以下操作:
{this.state.data.length>0?this.state.data[0]。当前:0;}

我猜数据可能是空白数组或其他数据类型…

试试以下方法:

更改:

{this.state.presentmonthdata.data[0] &&
    <Text style={{color: 'grey',fontSize: 30,   fontWeight: 'bold',  }}>
                            {this.state.presentmonthdata.data[0].present}
                  </Text>
{this.state.presentmonthdata.data[0]&&
{this.state.presentmonthdata.data[0].present}


{this.state.presentmonthdata.data!=未定义?this.state.presentmonthdata.data[0]。当前:null}

希望这有帮助!

尝试
this.state.presentmonthdata.data[0]。present
我收到一个错误“无法读取未定义的属性“0”。由于您正在从API获取数据,您应该等待数据加载。
this.state.presentmonthdata.data[0]&this.state.presentmonthdata.data[0].present
我遇到了相同的错误我确实更新了代码,但遇到了相同的错误请检查我遇到了错误“无法读取未定义的“{”消息的属性“0”:“本月存在”,“数据”:[{“present”:10}],“status”:“1”}问题是您没有在响应中解析JSON,并且设置了一个JSON。请在返回响应之前使用response.JSON()。您的值和键用“”包装,这就是问题所在
<Text>
{this.state.presentmonthdata.data!= undefined ? this.state.presentmonthdata.data[0].present: null}
</Text>