【问题标题】:React fetching data from api, and display as list in real-timeReact从api中获取数据,并实时显示为列表
【发布时间】:2023-02-16 18:27:22
【问题描述】:

我想从我的本地 api 获取数据,并显示实时更新。 从对象中获取并显示为列表,我有,并且工作正常,但是当 api 上有新数据时,列表不会更新。

有人可以向我解释我的示例需要什么来实时更新数据获取和显示吗?

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

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    }
  }

  componentDidMount() {
    var params = {
      method: 'GET',
      headers: {
        "cache-control": 'no-cache',
        pragma: 'no-cache',
      }
    };

    return fetch('http://192.168.1.54:8000/api/measurement', params)
    .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.log(error);
      }
    );
  }

  render() {
    if(this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      )
    } else {
      let measurements = this.state.dataSource.map((val, key) => {
        return  <View key={key} style={styles.item}>
                  <Text>{val.hardwareUnit} - {val.measurementType} : {val.value}</Text>
                </View>
      });

      return (
        <View style={styles.container}>
          <Text style={styles.title}>Measurements</Text>
          {/* Display the latest 5 measurements from API */}
          {measurements.slice(Math.max(measurements.length - 5, 0))}
        </View>
      )
    }
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你需要实施插座.进行更改时从后端触发事件,并在前端侦听这些更改。收到事件后,在前端进行所需的更改

    【讨论】:

      【解决方案2】:

      你需要什么叫做:websockets

      【讨论】:

        猜你喜欢
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 2018-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多