我有一个 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("");
};
答案 0 :(得分:1)
在createNewPost
方法中,帖子添加成功后,您必须将新帖子推送到您的状态。
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) => {
// success!
setPosts([...posts, postData]);
return data.json();
});
};
当然,postData
必须与 posts
数组中的单个帖子的架构匹配才能使其工作。
最好的解决方案是让后端将新帖子作为 JSON 对象返回,然后更新 posts
数组。
答案 1 :(得分:0)
一个简单的解决方法是您可以操纵“posts”变量的状态。 在您的 createNewPost 中,如果 Promise 成功返回且没有任何错误或异常,即进入“then”块,您可以将新帖子 -> {title: "new post", body: post} 附加到已获取的“帖子” “ 多变的。这样状态就会更新,你会看到新的帖子。
即
let prevPosts = [...posts];
prevPosts.push(newPost);
setPosts(prevPosts); // Append at last. You can even push at first index, that way post will appear at top.
因此,即使您刷新,也会加载新帖子,因为您在提交帖子时已经在后端进行了创建查询,然后更新了帖子变量。