如何获取 SPA(反应钩子)中的当前状态?

时间:2021-02-22 08:23:07

标签: reactjs single-page-application

我创建了一个博客(单页应用程序)。我可以在一个页面中看到每个帖子。我点击编辑更新内容。跳转到编辑页面时,如何获取编辑页面中singlePost的当前状态?我可以在不同的页面中将状态作为道具传递吗?谢谢!

singlePostPage.js

const { id } = useParams();
  const [singlePost, setSinglePost] = useState(null);
  const history = useHistory();

  useEffect(() => {
    getSinglePost(id).then((data) => setSinglePost(data[0]));
  }, [id, singlePost]);

  useEffect(() => {
    return () => setSinglePost(null);
  }, []);

  const handleDeletePost = () => {
    deletePost(id).then(() => history.push("/"));
  };

  const handleEditPost = () => {
    history.push(`/editPost/${id}`);
  };

  return (
    <PostPageContainer>
      {singlePost && <h1>{singlePost.title}</h1>}
      {singlePost && <h4>{timeConverter(singlePost.createdAt)}</h4>}
      <PostContent>{singlePost && singlePost.body}</PostContent>
      {singlePost && <button onClick={handleEditPost}>Edit</button>}
      {singlePost && <button onClick={handleDeletePost}>Delete</button>}
    </PostPageContainer>
  );

editPostPage.js

const { id } = useParams();
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [errorMessage, setErrorMessage] = useState();

  const history = useHistory();

  const handlePostSubmit = () => {
    updatePost({ title, content, id }).then((res) => {
      if (res.ok === 0) {
        return setErrorMessage(res.message);
      }
      history.push("/");
    });
  };

  const handleTitleChange = (e) => {
    setTitle(e.target.value);
  };

  const handleContentChange = (e) => {
    setContent(e.target.value);
  };

  return (
    <PostFormContainer>
      <PostForm onSubmit={handlePostSubmit}>
        <TitleInput type="text" onChange={handleTitleChange} value={title} />
        <ContentInput
          onChange={handleContentChange}
          value={content}
          rows="10"
        />
        <SubmitBtn>Submit</SubmitBtn>
      </PostForm>
    </PostFormContainer>
  );

1 个答案:

答案 0 :(得分:1)

使用您在此处遵循的方法,几乎​​没有方法可以实现您的期望。

由于您使用路由导航到编辑页面,因此您可以使用路由中的查询参数从状态传递值。 (这并不理想,因为博客文章可能包含长字符串)

处理这种情况的最佳方法是使用状态管理库 (Redux) 或 React Context API。

因此,您必须全局管理您的状态,并将所需的详细信息从全局状态提取到页面。