React-Native:解析简单的JSON GET / POST并每隔X秒刷新一次

问题描述 投票:0回答:1

从JSON响应获取数据并填充字段并每隔X秒刷新一次。仅在屏幕处于活动状态时,这不必是后台任务。

响应将是:res.name和res.host。它还将加载当前图像:res.imgurl

我已经尝试过下面的代码,但是react站点上的示例非常复杂并且使用列表,我只具有简单的JSON数据,没有数组。

import { StyleSheet, Text, View } from 'react-native';

export default function App() {

  fetch("https://broadcast.truthnetwork.com/play-currentshow.lasso?station=WTRU")
    .then(res => res.json())
    .then(res => {
      console.log("Server response :- \n", res);
  })
    .catch(error => {
      console.log("Error from server :- \n", error);

  });

  return (
    <View style={styles.container}>
      <Text style={styles.sometext}>Show Name:</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { 
    flex: 1,
    backgroundColor: '#375963',
    alignItems: 'center',
    justifyContent: 'center',
  },
  sometext: {
    color: '#ffffff'
  }
});

这是示例JSON响应:

{
"name": "Encouraging Word", 
"imgurl": "https://broadcast.truthnetwork.com/_img/shows300/4B0FA4EA116331D9A1WH3AE062F0.jpg", 
"description": "This is a simple description", 
"slug": "encouraging-word-don-wilton", 
"weburl": "http://www.theencouragingword.org/", 
"feedurl": "http://feeds.feedburner.com/tewfbs", 
"host": "Don Wilton", 
"showid": "69"
}

我希望应用程序每隔15-30秒提取JSON并显示当前的节目,节目图像和节目主持人并刷新数据(无需激活后台任务,仅在屏幕处于活动状态时。)>>

注意:此API将与station = WTRU上的GET或POST一起使用

从JSON响应获取数据并填充字段并每隔X秒刷新一次。仅在屏幕处于活动状态时,这不必是后台任务。响应为:res.name和res ....

json react-native polling
1个回答
0
投票

以下方法可能会派上用场。以下示例使用JavaScript的setInterval每5秒从API提取数据。一旦组件首次渲染,我们就以componentDidMount方法发出请求,并在componentWillUnmount内部的组件unmounts

© www.soinside.com 2019 - 2024. All rights reserved.