【发布时间】:2021-06-02 10:27:00
【问题描述】:
我有一个react 前端应用程序,后端有nodejs/express 和typeorm/mysql。我已经构建了 twitter 的“新闻提要”的克隆,我们可以在其中发布新的推文(文章)。在顶部,我有一个输入字段,用户可以在其中提交新帖子。一旦用户提交了新帖子,他必须刷新页面才能看到新帖子。如何在不重新加载应用程序或在提交后看到新帖子的情况下实现“实时重新加载”。我正在使用 useEffect() 钩子和 fetch 发送 HTTP 请求以与后端通信。
从主页获取帖子并创建新帖子的代码:
const [posts, setPosts] = React.useState([]);
const [isLoaded, setIsLoaded] = React.useState(false);
const [error, setError] = React.useState(null);
const [post, setNewPost] = React.useState("");
React.useEffect(() => {
fetch(`${serverUrl()}/posts`)
.then((res) => res.json())
.then(
(posts) => {
setIsLoaded(true);
setPosts(posts);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
const createNewPost = async (postData) => {
return fetch(`${serverUrl()}/posts`, {
method: "POST",
// add new
headers: { "Content-type": "application/json", userid: token },
body: JSON.stringify(postData),
}).then((data) => {
return data.json();
});
};
const handleSubmit = async (e) => {
e.preventDefault();
await createNewPost({ title: "Lorem ipsum", body: post });
setNewPost("");
};
【问题讨论】:
-
你能分享你的代码吗?尤其是存储所有博客文章的部分。
-
@Keimeno 我目前存储在组件的状态中。刚刚添加了用于获取和创建帖子的状态和钩子/方法
标签: mysql node.js reactjs express typeorm