0

我在 react.js 中有一个秒表。秒表结束后,用户可以将他们的时间存入数据库。在 index.js 文件中,我将<App />其与 util.js 一起调用。

应用程序.js

import React from 'react';
import { addName } from "./util";

function App() {
  const [name, setName] = React.useState("")

  function handleUpdate(evt) {
    setName(evt.target.value);
  }

  async function handleAddName(evt) {
    await addName(name);
  }

  return <div>
    <p><input type='text' value={name} onChange={handleUpdate} /></p>
    <button className='button-style' onClick={handleAddName}>Add Name</button>
  </div>
}

export default App;

实用程序.js

import "isomorphic-fetch"

export function addName(name) {
    return fetch('http://localhost:3001/addtime', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, time: Date.now() })
    })
}

它将他们的名字和时间放在数据库中,但它们是奇怪的时代。 在此处输入图像描述

这些时间中的每一个在秒表上都在 1 到 2 秒之间。我的节点 server.js 文件中有以下内容:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
...
app.post("/addtime", cors(), async (req,res) => {
    const name = req.body.name;
    const time = req.body.time;
    // const timeStamp = dateFormat(time, dateFormat.masks.isoDateTime);
    
    const template = 'INSERT INTO times (name,time) VALUES ($1,$2)';
    const response = await pool.query(template, [name,time]);
    
    res.json({name: name, time: time});

});

我不明白为什么要把这些奇怪的数字放在数据库中

4

1 回答 1

2

因此,您在数据库中看到的数字只是从 1970 年 1 月 1 日 00:00:00 UTC 开始的毫秒数,这是一个有用的数字,您在跟踪事件发生的时间时会经常使用它。现在我明白了1610330957356。所以这个数字并不罕见。

我怀疑你遇到的问题可能只是逻辑,我猜你希望看到一个以秒为单位的数字(也许以毫秒为单位),因为你提到这是某种秒表,这意味着你需要发送时间差,从秒表开始到停止。

您将如何进行此操作仍将使用Date.now(),但方式如下所述。

const start_time = Date.now(); // 1610330952000
// ... wait for stopwatch to stop or other events ...
// when the stop has triggered you need
const stop_time = Date.now(); // 1610330957000 after exactly 5 seconds of waiting
const difference = stop_time - start_time // 5000 for 5 seconds

那么你的身体将会JSON.stringify({ name, time: difference })

当然,您可以将这些压缩成更少的行,但我只是希望步骤清晰。

编辑:为了更清楚,这里是文档所说的返回

一个数字,表示自 UNIX 纪元以来经过的毫秒数。

来自 MDN 的 Date.now 文档

于 2021-01-11T02:15:11.440 回答