【问题标题】:Clone moment js object克隆时刻 js 对象
【发布时间】:2019-02-19 06:34:27
【问题描述】:

我的状态中有 momentjs 对象

  state = {
     startDate: getNow() //this funtion return a momemtJS object
    }

在一个函数中,我需要获取 startDate 前一年的日期

const dateBeforeOneYear = this.state.startDate.subtract(1, 'years');

但如果我这样做,我会错误地修改状态

所以我尝试复制状态

const copyStartDate = {...this.state.startDate}

const copyStartDate = this.state.startDate.subtract(1, 'years');

但现在我得到了错误,substract 不是一个函数,我猜是因为 copyStartDate 不再是 MomemntJs

【问题讨论】:

  • 仅将日期存储在状态变量中,只要您希望时刻对象将日期传递给时刻,我认为这将是一种更好的方法。

标签: reactjs momentjs


【解决方案1】:

There's a method 克隆时刻对象:

const yearBefore = this.state.startDate.clone().subtract(1, 'years');

在组件状态中存储日期的可序列化表示也是一个更好的主意,例如在 Date 或 Moment 上调用 .valueOf() 的结果,其中任何一个都返回自UNIX 纪元。

【讨论】:

    【解决方案2】:

    moment.js 有自己的 api 用于克隆 moment 对象。

    var copy = momentObj.clone();

    我同意在存储中存储日期序列化表示而不是对象。

    【讨论】:

      【解决方案3】:

      也可以通过它的构造函数复制moment 对象。像这样

      const firstMoment = moment("2020-08-18");
      const clone = moment(firstMoment);
      

      【讨论】:

        猜你喜欢
        • 2011-03-29
        • 1970-01-01
        • 2011-11-07
        • 2021-12-28
        • 1970-01-01
        • 2013-01-03
        • 2017-02-11
        • 2011-07-10
        • 1970-01-01
        相关资源
        最近更新 更多