【问题标题】:Using react.js, putting strange numbers in database使用 react.js,将奇怪的数字放入数据库
【发布时间】:2021-04-16 00:29:38
【问题描述】:

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

App.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;

util.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});

});

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

【问题讨论】:

  • 如果我现在在 javascript 控制台中输入 Date.now(),我会得到 1610330837963

标签: javascript node.js reactjs postgresql


【解决方案1】:

因此,您在数据库中看到的数字只是从 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 纪元以来经过的毫秒数。

Date.now Documentation from MDN

【讨论】:

  • 我很难理解我可以把 start_time 和 end_time 放在哪里。我将它们与程序的主要部分一起放在我的 index.js 中,然后尝试将我的结果导入 util.js,但这给了我一个 UnhandledPromiseRejectionWarning 和 DeprecationWarning。
  • @AustinStory 不幸的是,从您发布的代码中,我无法轻易指出,但我会尽我所能帮助您。您应该更新 addName 以还需要一个时间变量,并通过它。至于你在哪里计算这个时间差,这将在处理秒表的反应组件中。当你开始时,你需要更新一个存储开始时间的状态,当你停止时,你需要更新一个停止时间(或直接是总时间)状态。我假设您可能有另一个触发“发送”的按钮,并且您传递了时间变量。
猜你喜欢
  • 1970-01-01
  • 2014-02-06
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多