javascript - React:从 Node.js 服务器转换对象列表中的时间戳并保存到状态
问题描述
我的问题是关于如何:
- 通过传入的对象的获取数据数组进行映射
- 在创建这些对象时提取每个这些对象中的时间戳属性
- 将这些时间戳转换为
new Date(item.timestamp).toLocaleString()
或类似 - 将这些新转换的时间戳存储在“原始”对象数组中
- 最后将此数组存储在项目状态中
这是我到目前为止所拥有的:
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 社区的朋友...
这里想到了一些想法:
- 你能在你的服务器上做时间戳转换吗?
const timestamp = new Date().toLocaleString()
{ timestamp: timestamps }
就个人而言,我不会将items
. 似乎最好将其分开,因为它们是不同的形状,并且该对象与“项目”不同。- 如果您无法在服务器上进行时间戳转换,那么在渲染时进行时间戳转换似乎
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 - CSS text-decoration:underline 自动应用于容器中的所有元素
- automation - 在赛普拉斯中使用 id/name 登录表单访问元素的问题
- python - tkinter - 如何从类创建的条目中获取文本
- node.js - Google Cloud Run 中的结构化日志未被解析(使用 Winston 进行日志记录)
- mysql - 在codeigniter中将int date插入数据库表中
- sql - 如何计算特定日期第一次出现唯一 ID 的次数?
- maven - 不再支持源选项 6。使用 7 或更高版本
- c++ - 我不能通过引用捕获传递 lambda
- python-3.x - 如何将长列表拆分为具有相同成员的每一列
- mule - NameResolvingRequestBuilder$RotateIpListFactory 从骡子流调用外部休息 URL 时出错