首页 > 解决方案 > React:从 Node.js 服务器转换对象列表中的时间戳并保存到状态

问题描述

我的问题是关于如何:

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

下面的代码给了我这个: 在此处输入图像描述

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

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

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

随意询问是否有任何我需要澄清的地方。

提前谢谢你

埃里克

标签: javascriptnode.jsreactjstypescript

解决方案


这里是 React 和 TypeScript 社区的朋友...

这里想到了一些想法:

  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>
      ))}
    </>
  )
}

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


推荐阅读