【问题标题】:How can I update my news feed after I add new post添加新帖子后如何更新我的新闻提要
【发布时间】:2021-06-02 10:27:00
【问题描述】:

我有一个react 前端应用程序,后端有nodejs/expresstypeorm/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


【解决方案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 数组。

【讨论】:

  • 谢谢!它应该更新状态以导致页面“刷新”。
【解决方案2】:

一个简单的解决方法是您可以操纵“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.

因此,即使您刷新,也会加载新帖子,因为您在提交帖​​子时已经在后端进行了创建查询,后来又更新了帖子变量。

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2017-05-21
    相关资源
    最近更新 更多