React 从 API 获取数据,并实时以列表形式显示

huangapple go评论73阅读模式
英文:

React fetching data from api, and display as list in real-time

问题

我想从我的本地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>
      )
    }
  }
}
英文:

I want to fetch data from my local api, and display with real-time updating.
The fetch and display as list from object, i have, and it works fine, but the list is not updating when new data is available on the api.

Can someon explain to me what is needed in my example, to make real-time updating of data fetching and display?

import React from &#39;react&#39;;
import { StyleSheet, Text, View, ActivityIndicator } from &#39;react-native&#39;;
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
var params = {
method: &#39;GET&#39;,
headers: {
&quot;cache-control&quot;: &#39;no-cache&#39;,
pragma: &#39;no-cache&#39;,
}
};
return fetch(&#39;http://192.168.1.54:8000/api/measurement&#39;, params)
.then((response) =&gt; response.json())
.then((responseJson) =&gt; {
this.setState({
isLoading: false,
dataSource: responseJson,
});
})
.catch((error) =&gt; {
console.log(error);
}
);
}
render() {
if(this.state.isLoading) {
return (
&lt;View style={styles.container}&gt;
&lt;ActivityIndicator /&gt;
&lt;/View&gt;
)
} else {
let measurements = this.state.dataSource.map((val, key) =&gt; {
return  &lt;View key={key} style={styles.item}&gt;
&lt;Text&gt;{val.hardwareUnit} - {val.measurementType} : {val.value}&lt;/Text&gt;
&lt;/View&gt;
});
return (
&lt;View style={styles.container}&gt;
&lt;Text style={styles.title}&gt;Measurements&lt;/Text&gt;
{/* Display the latest 5 measurements from API */}
{measurements.slice(Math.max(measurements.length - 5, 0))}
&lt;/View&gt;
)
}
}
}

答案1

得分: 4

需要实现sockets。在后端进行更改时触发一个事件,然后在前端监听这些更改。在接收到事件时,在前端进行所需的更改。

英文:

You need to implement sockets. Trigger an event from backend when changes are made and listen for those changes on frontend. On receiving event make the required changes on frontend

答案2

得分: 3

为了呈现新数据,您需要首先拥有它。为此,您将需要组件来请求数据源。如果它是后端服务器,您可以考虑轮询它,如果您所需的数据不需要非常精确,而且您的应用程序可以处理一些延迟。但这将给服务器带来一些压力。但只要轮询请求具有正确的标识符,您可以继续在服务器上使用无状态方法。

在这里,您可以设置一个间隔,轮询服务器以获取数据并重新注入状态。

或者,您可以建立一个 WebSocket 连接。但这可能需要根据您的用例在服务器上维护一些状态。

参考链接:https://blog.logrocket.com/websocket-tutorial-real-time-node-react/

另外,您还可以使用服务器发送事件(在上述文章中有描述)。但对于大多数情况而言,我发现这比 WebSocket 更具挑战性。如果您不需要向服务器发送任何更新,这也可以起作用。

参考链接:https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

英文:

In order to render new data, you need to first have it. For this you will need the component to ask the data source. If it is a backend server, you can consider polling it, if the data you need does not need to be very accurate and can your app can handle some delays. But this will place some strain on the servers. But you can continue to use the stateless approach on the server and get away with it so as long as the polling request has the right ids.

Here one can set an Interval, poll the server to fetch data and rehydrate the state easily.

Alternatively you can set up a web socket connection. However this may need to maintain some state on the server depending on your use case.

Ref: https://blog.logrocket.com/websocket-tutorial-real-time-node-react/

Alternatively you can use Server Sent Events (again described in the article above.). But this I have felt to be a bigger challenge than web sockets for most cases. If you do not need to send any updates to the server, this could work as well.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

答案3

得分: 2

你需要的东西叫做:websockets。

英文:

what you need its called: websockets

huangapple
  • 本文由 发表于 2023年2月16日 18:23:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定