![](/img/trans.png)
[英]I want to set the fetched data from firestore as initial value of useState
[英]How do I use data that I fetched from DB in useState?
所以我正在使用 useEffect 挂钩从数据库中获取我的数据,在我获得该数据后,我想将其设置为 title 和 postBody 的 useState,但它不起作用,因为 useEffect 挂钩“最后”运行,我该如何修复它?
代码:
const [cPost, setCPost] = useState([]);
const postId = id.match.params.id;
useEffect(() => {
axios.get('http://localhost:5000/posts/'+postId)
.then(posts => {
setCPost(posts.data);
console.log("SAS");
})
}, []);
const [title, setTitle] = useState(cPost.title);
const [postBody, setPostBody] = useState(cPost.postBody);
作为临时快速的解决方案,您可以使用以下解决方法:
const [cPost, setCPost] = useState();
const [title, setTitle] = useState();
const [postBody, setPostBody] = useState();
const postId = id.match.params.id;
useEffect(() => {
axios.get('http://localhost:5000/posts/'+postId)
.then(post => {
setCPost(post.data);
console.log("SAS");
})
}, []);
useEffect(() => {
if(cPost) {
setTitle(cPost.title);
setPostBody(cPost.postBody);
}
}, [cPost]);
或第二个选项:
const [cPost, setCPost] = useState();
const [title, setTitle] = useState();
const [postBody, setPostBody] = useState();
const postId = id.match.params.id;
useEffect(() => {
axios.get('http://localhost:5000/posts/'+postId)
.then(post => {
setCPost(post.data);
setTitle(post.title);
setPostBody(post.postBody);
console.log("SAS");
})
}, []);
但在未来,我会建议使用特殊库或创建hook
来发出API
请求等side effects
,或创建钩子来发出API
请求。
PS并考虑是否需要将title
和body
分别存储在组件state
中。 我强烈怀疑你不需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.