Javascript 反应:转换Node.js服务器中对象列表中的时间戳并保存到状态
我的问题是关于如何:Javascript 反应:转换Node.js服务器中对象列表中的时间戳并保存到状态,javascript,node.js,reactjs,typescript,Javascript,Node.js,Reactjs,Typescript,我的问题是关于如何: 通过对象的传入获取数据数组映射 在创建这些对象时,提取每个对象中的时间戳属性 将这些时间戳转换为新日期(item.timestamp).toLocaleString()或类似格式 将这些新转换的时间戳存储在对象的“原始”数组中 最后将此数组存储在item state中 下面的代码告诉我: 这就是我到目前为止所做的: import React, { useState, useEffect } from "react"; import { Link } fro
新日期(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;
我这样想对吗?我应该在将数组保存到状态之前执行此操作,还是可以在呈现时间戳之前执行此操作
请随时询问我是否有什么需要澄清的
先谢谢你,
Erik这里是React和TypeScript社区的朋友 这里我想到了一些想法:
{timestamp:timestamps}
存储在与项
相同的状态中。看起来最好将它们分开,因为它们是不同的形状,并且这个对象与“项目”不同项时进行时间戳转换似乎比在获取项时进行时间戳转换更好
const PostList:React.FC=()=>{
// ...
返回(
{items.map(item=>(
{项目标题}
{item.text}
{新日期(item.timestamp).toLocaleString()}
))}
)
}
很明显,这在很大程度上是一种设计选择。但希望这有助于分享一些关于如何处理这一问题的非偏见想法。希望这有帮助
Joe是React和TypeScript社区的朋友 这里我想到了一些想法:
{timestamp:timestamps}
存储在与项
相同的状态中。看起来最好将它们分开,因为它们是不同的形状,并且这个对象与“项目”不同项时进行时间戳转换似乎比在获取项时进行时间戳转换更好
const PostList:React.FC=()=>{
// ...
返回(
{items.map(item=>(
{项目标题}
{item.text}
{新日期(item.timestamp).toLocaleString()}
))}
)
}
很明显,这在很大程度上是一种设计选择。但希望这有助于分享一些关于如何处理这一问题的非偏见想法。希望这有帮助
乔
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}...`));