如何正确地将DateTime字符串通过MOBX-State-Tree将日期对象转换为日期对象

发布于 2025-01-19 17:58:23 字数 713 浏览 2 评论 0原文

有传入的字符串数据是日期时间格式,

其映射此对象罚款;

import { types } from 'mobx-state-tree'

export const UserCard = types.model('UserCard').props({
  id: types.number,
  awarded_at: types.maybeNull(types.string),
})

在路径“/0/warded_at”值” 2022-01-25T21:07:30.473502+00:00:00“无法分配给类型:(date | null)

但是由于它的日期尝试此模型只是将字符串更改为日期;

export const UserCard = types.model('UserCard').props({
  id: types.number,
  awarded_at: types.maybeNull(types.Date),
})

然后在设置对象时获得此错误;

在路径“/0/warded_at”值” 2022-01-25T21:07:30.473502+00:00:00“是 不能分配给类型:(日期| null)

因此如何将传入的字符串数据映射到日期对象

there is incoming string data which is date time format,

Its mapping this object fine;

import { types } from 'mobx-state-tree'

export const UserCard = types.model('UserCard').props({
  id: types.number,
  awarded_at: types.maybeNull(types.string),
})

at path "/0/awarded_at" value "2022-01-25T21:07:30.473502+00:00" is not assignable to type: (Date | null)

but since its datetime trying this model just changed string to date;

export const UserCard = types.model('UserCard').props({
  id: types.number,
  awarded_at: types.maybeNull(types.Date),
})

then get this error in setting object;

at path "/0/awarded_at" value "2022-01-25T21:07:30.473502+00:00" is
not assignable to type: (Date | null)

So how to map incoming string data to Date object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渔村楼浪 2025-01-26 17:58:23

一种常见的技术是像您在第一个片段中所做的那样将其建模为字符串,创建一个创建date的视图,然后使用它:

import { types } from "mobx-state-tree";

export const UserCard = types
  .model("UserCard")
  .props({
    id: types.number,
    awarded_at: types.maybeNull(types.string)
  })
  .views((self) => ({
    get awardedAtDate() {
      return new Date(self.awarded_at);
    }
  }));

const userCard = UserCard.create({
  id: 1,
  awarded_at: "2022-01-25T21:07:30.473502+00:00"
});

console.log(userCard.awardedAtDate instanceof Date, userCard.awardedAtDate);
// true, Tue Jan 25 2022 22:07:30 GMT+0100 (Central European Standard Time)

如果您不喜欢该方法上方您可以创建自定义类型:

import { types } from "mobx-state-tree";

function validateDate(str) {
  const date = Date.parse(str);
  if (isNaN(date)) throw new Error("Invalid date");

  return new Date(date);
}

export const IsoDate = types.custom({
  name: "IsoDate",
  fromSnapshot(value) {
    return validateDate(value);
  },
  toSnapshot(value) {
    return value.toISOString();
  },
  isTargetType(maybeDate) {
    return maybeDate instanceof Date;
  },
  getValidationMessage(snapshot) {
    // If we don't throw an error here when the snapshot is faulty (e.g. null),
    // things like types.maybeNull(IsoDate) will not work properly
    try {
      validateDate(snapshot);
      return "";
    } catch (error) {
      return error.message;
    }
  }
});

export const UserCard = types.model("UserCard").props({
  id: types.number,
  awarded_at: types.maybeNull(IsoDate)
});

const userCard = UserCard.create({
  id: 1,
  awarded_at: "2022-01-25T21:07:30.473502+00:00"
});

console.log(userCard.awarded_at instanceof Date, userCard.awarded_at);
// true, Tue Jan 25 2022 22:07:30 GMT+0100 (Central European Standard Time)

One common technique is to model it as a string like you have done in your first snippet, create a view that creates a Date out of it, and use that instead:

import { types } from "mobx-state-tree";

export const UserCard = types
  .model("UserCard")
  .props({
    id: types.number,
    awarded_at: types.maybeNull(types.string)
  })
  .views((self) => ({
    get awardedAtDate() {
      return new Date(self.awarded_at);
    }
  }));

const userCard = UserCard.create({
  id: 1,
  awarded_at: "2022-01-25T21:07:30.473502+00:00"
});

console.log(userCard.awardedAtDate instanceof Date, userCard.awardedAtDate);
// true, Tue Jan 25 2022 22:07:30 GMT+0100 (Central European Standard Time)

If you don't like the approach above you can create a custom type:

import { types } from "mobx-state-tree";

function validateDate(str) {
  const date = Date.parse(str);
  if (isNaN(date)) throw new Error("Invalid date");

  return new Date(date);
}

export const IsoDate = types.custom({
  name: "IsoDate",
  fromSnapshot(value) {
    return validateDate(value);
  },
  toSnapshot(value) {
    return value.toISOString();
  },
  isTargetType(maybeDate) {
    return maybeDate instanceof Date;
  },
  getValidationMessage(snapshot) {
    // If we don't throw an error here when the snapshot is faulty (e.g. null),
    // things like types.maybeNull(IsoDate) will not work properly
    try {
      validateDate(snapshot);
      return "";
    } catch (error) {
      return error.message;
    }
  }
});

export const UserCard = types.model("UserCard").props({
  id: types.number,
  awarded_at: types.maybeNull(IsoDate)
});

const userCard = UserCard.create({
  id: 1,
  awarded_at: "2022-01-25T21:07:30.473502+00:00"
});

console.log(userCard.awarded_at instanceof Date, userCard.awarded_at);
// true, Tue Jan 25 2022 22:07:30 GMT+0100 (Central European Standard Time)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文