我的问题是关于如何:
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}...`));
我是否正在考虑正确的方法?我应该在将数组保存为状态之前就执行此操作,还是可以在渲染时间戳之前就执行此操作?
随时问我是否需要澄清。
先谢谢您
Erik
答案 0 :(得分:0)
这里是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>
))}
</>
)
}
很明显,其中很多确实是设计选择。但是希望这有助于分享一些关于如何实现此目标的其他公正的想法。希望这会有所帮助!
乔