【问题标题】:React-Native reacts differently when not debugging remotely不远程调试时,React-Native 的反应不同
【发布时间】:2017-07-02 06:18:40
【问题描述】:
<Text style={s.date}>{ new Date(this.props.order.ordered_at).toLocaleDateString('en-US', { day: '2-digit', month: 'short' }) }</Text>
<Text style={s.time}>({ new Date(this.props.order.ordered_at).toLocaleTimeString('en-US', { hour: '2-digit', minute:'2-digit', hour12: true }) })</Text>

JS远程调试关闭时的输出

02/13/17 (23:51:31)
02/13/17 (23:48:07)

JS远程调试开启时的输出

Feb 13 (11:51 PM)
Feb 13 (11:48 PM)

是什么原因造成的,我该如何解决?

【问题讨论】:

  • 阅读official document了解更多信息,它解释得很好。作为替代方案,您可以使用 moment 代替 JS 日期 API。
  • 最好用 MomentJs

标签: javascript react-native remote-debugging


【解决方案1】:

在我开始使用以下代码之前,我遇到了同样的问题:

moment(`${post.date}+02:00`).

这里我使用了+02:00,因为服务器日期是 GMT+2 时区。您应该更改它以调整您的服务器日期时区

【讨论】:

    【解决方案2】:
    import moment from 'moment';
    
    <Text style={s.date}>{ moment(new Date(this.props.order.ordered_at)).format('ll') }</Text>
    <Text style={s.time}>{ moment(new Date(this.props.order.ordered_at)).format('LT') }</Text>
    

    将持续产出

    Feb 13, 2017 (11:51 PM)
    Feb 13, 2017 (11:48 PM)
    

    为什么通常的Date() 方式不起作用?

    JavaScript 运行时 使用 React Native 时,您将在两种环境中运行 JavaScript 代码:

    • 在 iOS 模拟器和设备、Android 模拟器和设备上,React Native 使用 JavaScriptCore,它是支持 苹果浏览器。在 iOS 上,JSC 不使用 JIT,因为没有可写的 iOS 应用中的可执行内存。
    • 在使用 Chrome 调试时,它会在 Chrome 本身中运行所有 JavaScript 代码,并通过 WebSocket 与本机代码进行通信。那么你 正在使用 V8。

    虽然这两种环境非常相似,但您最终可能会遇到一些问题 不一致。我们可能会尝试其他 JS 未来的引擎,所以最好避免依赖于 任何运行时。

    因此,如 cmets 中所述,最好使用 momentJS 而不是盲目依赖环境的 JS,这样做会导致 docs 中提到的不一致

    【讨论】:

    猜你喜欢
    • 2019-09-11
    • 2019-06-17
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多