我的问题是如何:
- 通过传入的对象获取数据数组进行映射
- 在创建这些对象时提取每个对象中的时间戳属性
- 将这些时间戳转换为
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 社区的 friend ...
这里想到了一些想法:
- 您可以在您的服务器上进行时间戳转换吗?
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 - React : Convert timestamps in list of objects from Node. js 服务器并保存到状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258950/