1

我正在使用现有代码库,现有代码从端点调用日期。预期值是一个 ISO 字符串(即"2020-01-09T07:41:02.6025984-05:00"):

// in my sagas:

export function* handleGetServerTime(): Generator {
  try {
    const response = (yield call(
      axios.get,
      "/api/server/time"
    )) as AxiosResponse;

    // Format the response time string into a Date object
    const time = new Date(response.data);
    console.log(time);

    yield put(ActionCreators.GetServerTimeSuccess.create(time));
  } catch (error) {
    // ...
  }
}

如您所见,代码获取 ISO 字符串,new Date从中创建 a,然后将其发送到 action 和 reducer,后者将其作为new Date.

当我打开我的 redux devtools 时,我再次看到一个 ISO 时间字符串:在此处输入图像描述

然而,上面的 console.log 语句打印了我们在运行new Date:时通常看到的内容Mon Apr 05 2021 11:56:25 GMT-0700 (Pacific Daylight Time)。当我进入控制台并检查store.getState().somewhere.timeFromServer.

redux devtools 是否有一些默认行为将Date对象显示为其 ISO 字符串?

请注意,我根本不喜欢这种编程模式——我宁愿存储从服务器返回的原始 ISO 字符串,并在我的前端代码中进行任何日期操作。这让我整个早上都陷入了循环,因为来自服务器的 ISO 字符串 f= 和 devtools 中显示的字符串不一样!从 ISO 字符串转换为 anew Date并再次转换将去除 UTC 时间偏移量,我不想丢失它。

4

1 回答 1

1

您不应将值保存在无法序列化的状态中,devtools 必须以某种方式显示 Date 对象(转换为文本),因此它们使用toISOString但此 iso 字符串已本地化为 Zulu 时间。为防止混淆,最好保存字符串,不要将其转换为日期并在选择器中进行转换。

于 2021-04-06T06:24:37.027 回答