javascript - React : Convert timestamps in list of objects from Node. js 服务器并保存到状态

标签 javascript node.js reactjs typescript

我的问题是如何:

  1. 通过传入的对象获取数据数组进行映射
  2. 在创建这些对象时提取每个对象中的时间戳属性
  3. 将这些时间戳转换为 new Date(item.timestamp).toLocaleString() 或类似的 enter image description here
  4. 将这些新转换的时间戳存储在“原始”对象数组内
  5. 最后将此数组存储在项目状态内

下面的代码给了我这个: enter image description here

这是我到目前为止所拥有的:

    import React, { useState, useEffect } from "react";
    import { Link } from "react-router-dom";

    interface PostListProps {}

    interface PostListState {
      id: number;
      heading: string;
      text: string;
      timestamp: number | string;
    }

    const PostList: React.FC<PostListProps> = () => {
      useEffect(() => {
        fetchItems();
      }, []);

      const [items, setItems] = useState<PostListState[]>([]);

      const fetchItems = async () => {
        try {
          const data = await fetch("http://localhost:3001/api/posts");
          const items = await data.json();
          const timestamps = items.map((item: any) => {
            return {
              timestamp: new Date(item.timestamp).toLocaleString()
            };
          });

          console.log("Before items is sent to state", timestamps);

          setItems([
            ...items,
            {
              timestamp: timestamps
            }
          ]);
          console.log("Right after items been sent to state", items);
        } catch (error) {
          console.error(error);
        }
      };

      return (
        <>
          {items.map(item => (
            <div key={item.id}>
              <h1>
                <Link to={`/posts/${item.id}`}>{item.heading}</Link>
              </h1>
              <p>{item.text}</p>
            </div>
          ))}
        </>
      );
    };

    export default PostList;

这是我在 Node.js 中的模拟服务器

const posts = [
  {
    id: 1,
    heading: "post 1",
    text: "This is a blogpost",
    timestamp: ""
  },
  {
    id: 2,
    heading: "post 2",
    text: "This is also blogpost",
    timestamp: ""
  }
];

app.get("/api/posts", (req, res) => {
  res.send(posts);
});

app.post("/api/posts", (req, res) => {
  const timestamp = Date.now();
  req.body.timestamp = timestamp;

  const post = {
    id: posts.length + 1,
    heading: req.body.heading,
    text: req.body.text,
    timestamp: timestamp
  };
  posts.push(post);
  res.send(post);
});

const port = process.env.PORT || 3001;
app.listen(port, () => console.log(`Listening on port ${port}...`));

我的思考方式正确吗?我应该在将数组保存到状态之前执行此操作,还是可以在渲染时间戳之前执行此操作?

如果有什么需要澄清的地方,请随时询问。

先谢谢你了,

埃里克

最佳答案

这里是 React 和 TypeScript 社区的 friend ...

这里想到了一些想法:

  1. 您可以在您的服务器上进行时间戳转换吗? const timestamp = new Date().toLocaleString()
  2. 就我个人而言,我不会将 { timestamp: timestamps } 存储在与 items 相同的状态中。似乎最好将其分开,因为它们的形状不同,并且该对象与“项目”不同。
  3. 如果您无法在服务器上进行时间戳转换,那么似乎在渲染 item 时进行时间戳转换可能比在 fetchItems 时进行更好。
const PostList: React.FC<PostListProps> = () => {
  // ...

  return (
    <>
      {items.map(item => (
        <div key={item.id}>
          <h1>
            <Link to={`/posts/${item.id}`}>{item.heading}</Link>
          </h1>
          <p>{item.text}</p>
          <p>{new Date(item.timestamp).toLocaleString()}</p>
        </div>
      ))}
    </>
  )
}

显然,其中很多实际上是设计选择。但希望这有助于分享一些关于如何处理此问题的额外无偏见想法。希望这有帮助!

关于javascript - React : Convert timestamps in list of objects from Node. js 服务器并保存到状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258950/

相关文章:

javascript - NodeJS 从哪里开始?

node.js - Node 检查器不启动

reactjs - React中依赖useState hook的条件渲染组件如何写测试?

node.js - 当未捕获错误时, Node : async. foreach 会默默失败,抛出异常

javascript - 悬停时的颜色没有改变

javascript - 如何访问原型(prototype)上的阴影 JavaScript 对象字段?

javascript - 使用 lodash 进行分组和分层映射

node.js - 类型错误 : Cannot read property 'list' of undefined of balanceTransactions

javascript - 在reactjs中调用方法内的方法

javascript - 如何通过ajax获取UTF-8格式的数据