javascript - reeact - 将 api 数据加载到 this.state 中以供文本使用
问题描述
我想了解为什么我的文本没有呈现,以及我怎样才能让它工作
import React, { Component } from 'react';
import { View,Button,Text } from 'react-native';
export default class LiveApiData extends Component {
constructor() {
super()
this.state = {data:[]}
}
componentDidMount() {
fetch("<<taking out the api key")
.then(response => response.json())
.then(new_data => {this.setState({data:new_data})})
}
render() {
return (
<View style={{ height: 200, flexDirection: 'row'}}>
<Text> {this.state.data[0]}</Text>
</View>
);
}
}
非常感谢提前
解决方案
在上面的 render() 代码中,您正在渲染作为数组的数据。如果此数组是对象的集合,您将需要指定键名来呈现文本。如果数组是字符串,那么它应该被渲染。
我正在为这个问题粘贴一个工作示例。示例链接
该解决方案将添加一个空检查。因为第一次渲染时状态会是空的。
<div style={{ height: 200, flexDirection: "row" }}>
<div> {this.state.data.length ? this.state.data[0].title : ""}. </div>
</div>
推荐阅读
- android - Android - 通过图像组件循环
- python - 在 Python 的面向对象编程中 self 如何工作?
- oracle - CURRENT_TIMESTAMP 最大长度
- xamarin.android - 如何使 EditText 成为焦点但不可点击?(Xamarin.Android)
- gradle - 从 gradle 调用 ant 时抛出 org.gradle.process.internal.ExecException
- c# - Unity - 实例化后游戏对象的错误定位
- hsts - hsts 预加载而不被列出?
- javascript - 在提交这个 post 请求时,主代码没有被执行,它总是到达 catch 块,为什么?
- kubernetes - 有没有办法知道应该在什么时候执行 pod?
- vue.js - 如何在 Vue Nuxt 项目中导入整个 SCSS 文件夹?