[英]Can't Render Data From API in react native
i want to render data from API, but when i want to view the data in render can't appear here my code, i got my error the data soal_id is undefined.我想渲染来自 API 的数据,但是当我想查看渲染中的数据时我的代码不能出现在这里,我得到了数据 soal_id 未定义的错误。 How to make appear the data with the true way?
如何使数据以真实的方式出现? when i try to show the another data this is same doesn't appear and showing error.
当我尝试显示另一个数据时,没有出现相同的数据并显示错误。
import React, { Component } from 'react'; import { View, Text } from 'react-native'; // import { cos } from 'react-native-reanimated'; export default class QuizTes extends Component { constructor(props) { super(props); this.state = { soal: [], index:0, }; } getSoal =()=>{ fetch('http://unnamed48.ccug.gunadarma.ac.id:9091/api/user/soal',{ method:'post', headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ token:"4266ae6eddc02afa38fa39477c22ab5f", studi:"penalaran umum" }) }).then(res => res.json()).then(getData =>{ // console.log(getData) if(getData){ this.setState({ soal: getData.data }) } }).catch(error =>{ console.log(error) }) } componentDidMount(){ this.getSoal() } nextSoal = ()=>{ this.setState({index:(this.state.index + 1) % this.state.soal.length}) } prevSoal = ()=>{ this.setState({index:(this.state.index - 1) % this.state.soal.length}) } render() { const item = this.state.soal[this.state.index] // var items = JSON.parse(item) // console.log(items) return ( <View> <Text> QuizTes </Text> <Text> {JSON.stringify(item).soal_id}/20 </Text> {/* <Text> {item.soal_pertanyaan} </Text> */} </View> ); } }
Dont use JSON.stringify
in your case.不要在你的情况下使用
JSON.stringify
。 In the render method, just make a check on item
and then render在渲染方法中,只需检查
item
然后渲染
Like this像这样
<Text> {item && item.soal_id}/20 </Text>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.