繁体   English   中英

如何在 useState 中使用从 DB 获取的数据?

[英]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请求。

例如redux-sagaredux-thunk

并使用 state 管理器,例如reduxmobx

PS并考虑是否需要将titlebody分别存储在组件state中。 我强烈怀疑你不需要它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM