首页 > 解决方案 > 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>
    );
  }
}

非常感谢提前

标签: javascriptreactjsreact-native

解决方案


在上面的 render() 代码中,您正在渲染作为数组的数据。如果此数组是对象的集合,您将需要指定键名来呈现文本。如果数组是字符串,那么它应该被渲染。

我正在为这个问题粘贴一个工作示例。示例链接

该解决方案将添加一个空检查。因为第一次渲染时状态会是空的。

<div style={{ height: 200, flexDirection: "row" }}>
    <div> {this.state.data.length ? this.state.data[0].title : ""}. </div>
</div>

推荐阅读