反应 - 每隔几秒重新渲染相对时间

时间:2021-06-08 01:16:21

I'm creating a real time application with React. I'm using Mobx as my state container. (doesn't matter, Redy

我正在用React创建一个实时应用程序。我正在使用Mobx作为我的状态容器。 (没关系,雷迪

I have a component showing relative time, since the last order has arrived. ( <FormattedRelative /> component taken from react-intl library - showing something like "1 minute ago"). This "1 minute ago" message gets snapshotted when UI gets rendered for the first time. But as the time goes, this gets outdated and inaccurate.

我有一个显示相对时间的组件,因为最后一个订单到了。 ( 组件取自react-intl库 - 显示类似“1分钟前”的内容)。当首次呈现UI时,此“1分钟前”消息将被快照。但随着时间的推移,这已经过时且不准确。

What do you think is the best and idiomatic approach to keep those messages up to date (let's say old at most 10 seconds)?

您认为保持这些消息最新的最佳和惯用方法是什么(让我们说最多10秒)?

Should I somehow schedule re-render with setInterval? Or should I periodically change some value in my store, so my UI gets re-rendered?

我应该以某种方式安排使用setInterval重新渲染?或者我应该定期更改商店中的某些值,以便重新呈现我的UI?

Thanks for any suggestion.

谢谢你的任何建议。

1 个解决方案

#1


0  

Try using react-timeago. it is highly customizable for international usage with support for Localization Ex:- A custom formatter with french strings

尝试使用react-timeago。它具有高度可定制性,适合国际使用,支持Localization Ex: - 带有法语字符串的自定义格式化程序

import TimeAgo from 'react-timeago'
import frenchStrings from 'react-timeago/lib/language-strings/fr'
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter'

const formatter = buildFormatter(frenchStrings)

// in your react component
<TimeAgo date='Feb 1, 1966' formatter={formatter} />

#1


0  

Try using react-timeago. it is highly customizable for international usage with support for Localization Ex:- A custom formatter with french strings

尝试使用react-timeago。它具有高度可定制性,适合国际使用,支持Localization Ex: - 带有法语字符串的自定义格式化程序

import TimeAgo from 'react-timeago'
import frenchStrings from 'react-timeago/lib/language-strings/fr'
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter'

const formatter = buildFormatter(frenchStrings)

// in your react component
<TimeAgo date='Feb 1, 1966' formatter={formatter} />