javascript - 如何使用 react-native 从 API 获取嵌套对象
问题描述
我正在使用 QOD API,我似乎无法从 Json 获取报价数据。这是我到目前为止所拥有的。我很确定我没有正确映射数据,因为数据记录正常。(请参阅附图),但我似乎无法得到它。我只需要作者和 imageUrl。非常感谢任何帮助或指导。
export default class QuoteScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
data: null,
error: null,
};
}
apiUrl = 'https://quotes.rest/qod';
getData = (ev) => {
this.setState({ loading: false, error: null });
let h = new Headers();
h.append('X-TheySaidSo-Api-Secret', '*******************My API key');
let req = new Request(this.apiUrl, {
headers: h,
method: 'GET',
});
fetch(req)
.then(response => response.json())
.then(this.showData)
.catch(this.ErrorMessage);
};
showData = (data) => {
this.setState({ loading: true, data });
console.log(data);
};
ErrorMessage = (err) => {
this.setState({ loading: true, error: err.message });
};
componentDidMount() { }
render() {
return (
<View styles={styles.container}>
{!this.state.loading && <Text>Loading</Text>}
<Text style={styles.txt}>Gimme Some Data</Text>
<Button title="GetData" onPress={this.getData} />
{this.state.error && (<Text style={styles.err}>{this.state.error}</Text>
)}
{this.state.data && this.state.data.length > 0 && (
this.state.data.map((contents) => (
<Text style={style.txt}>{contents.quotes}</Text>
))
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4C724',
},
txt: {
fontSize: 24,
color: '#333'
},
err: {
color: 'red',
fontSize: 30,
fontWeight: 'bold'
}
});
解决方案
您将整个对象数组放入 Text 中,不会显示任何内容
您需要当前地图中的另一张地图:
!!contents.quotes?.length &&
contents.quotes.map(quote=>{
return <Text style={style.txt}>{quote.author}</Text>
}
推荐阅读
- kubernetes - 迁移后的 Nginx 入口配置
- docker - 如何将 Docker 文件夹移动到另一个磁盘?
- android - 如何在 CameraX 中镜像 PreviewView?
- javascript - 防止用户在多项选择题(ReactJS)中两次点击相同的正确答案
- json - 如何在 React.js 中使用 api 变量和动态 js 变量设置 useState 常量变量
- flutter - 将两个文本居中到 AppBar
- powershell - 如何使用 powershell 将文件上传到匿名文件
- javascript - 如何在使用 JQuery 离开页面之前显示对话框
- vue.js - Storybook nuxt build 不包括装饰器
- authentication - 具有证书身份验证的 Ansible WinRM 被模拟令牌停止