React-Native fetch 示例未呈现 [英] React-Native fetch example not rendering

查看:77
本文介绍了React-Native fetch 示例未呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 和 React-Native 的新手,并在 官方网站.我正在使用 fetch 对我的 API 端点进行 get 调用.返回的 JSON 显示在开发人员工具的控制台上,但未在应用程序中呈现.我可以看到所有控制台日志,但不能在应用程序上看到.

I am new to React and React-Native and following the docs of React native on the official website. I am making a get call to my API endpoint using fetch. The returned JSON is being shown on the console in Developer's tool but it is not rendering in the Application. I can see all the console logs but not on the Application.

此外,如果我将 FetchExample 组件设为默认类,则 UI 呈现良好.问题出在哪儿?请帮忙.

Moreover, if I make my FetchExample Component as default class, then the UI is rendering fine. Where is the problem? Please Help.

class FetchExample extends Component {
  constructor(props){
    super(props);
    this.state ={ isLoading:true}
  }
  componentDidMount(){
      console.log(" mounting")
      return fetch('https://evening-escarpment-86286.herokuapp.com/todo')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }
  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    console.log(this.state.dataSource);
    console.log("hi")
    return(
      <View style={{flex: 1, paddingTop:20}}>

        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.id}, {item.name}, {item.message}, {item.time}</Text>}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component{
  render(){
    return (
      <View style={{alignItems: 'center',  marginTop: 30}}>
        <FetchExample />
      </View>
    );
  }
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings);

推荐答案

嗯,这个问题是通过将 API 调用(fetch)放在构造函数本身而不是 componentDidMount 方法中来解决的.虽然我认为这对于 React-Native 文档 来说不是一个好方法说我们应该在 componentDidMount 方法中进行 API 调用.

Well, this thing was solved by putting the API call(fetch) in the constructor itself and not in componentDidMount method. Although I don't think it's a good way as for React-Native documentation says we should make API calls in the componentDidMount method.

这篇关于React-Native fetch 示例未呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆