reactjs - 如何在 SPA (react hooks) 中获取当前状态?
问题描述
我创建了一个博客(单页应用程序)。我可以在一个页面中看到每个帖子。我单击编辑以更新内容。跳转到编辑页面时,如何获取编辑页面中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>
);
编辑PostPage.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>
);
解决方案
使用您在此处遵循的方法,几乎没有什么方法可以实现您的期望。
由于您使用路由导航到编辑页面,因此您可以使用路由中的查询参数从状态传递值。(这并不理想,因为博客文章可以包含长字符串)
处理这种情况的最佳方法是使用状态管理库(Redux)或 React Context API。
因此,您必须全局管理您的状态,并将所需的详细信息从全局状态提取到页面。
推荐阅读
- android - 摆脱原生反应中的测试错误
- sql - SQL:内存不足错误 | Heroku Postgres + Hasura GraphQL
- accessibility - 屏幕阅读器在元素展开时阅读内容
- java - 如何使用 Java 中的 EditorConfig 在 IntelliJ IDEA 中关闭其自己的行上的右括号?
- html - 如何在不考虑地址栏的情况下正确计算移动设备上的视口高度?
- ios - 无主变量和异步函数
- r - 用组的第一次观察替换所有值
- c - 在递归函数中使用静态
- java - AWS CDK Vpc.GetPublicSubnets() 返回错误数量的公有子网
- python - Python - 当小时值大于 24 时将字符串解析为 timedelta