【问题标题】:How do I use data that I fetched from DB in useState?如何在 useState 中使用从 DB 获取的数据?
【发布时间】:2021-03-29 08:37:18
【问题描述】:

所以我正在使用 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);

【问题讨论】:

    标签: javascript reactjs react-hooks components


    【解决方案1】:

    作为一种临时快速的解决方案,您可以使用这样的解决方法:

    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");
        })
    }, []);
    

    但在未来,我建议使用特殊库执行 side effects 之类的 API 请求和其他请求,或者创建 hook 以发出 API 请求。

    例如redux-sagaredux-thunk

    并使用像 reduxmobx 这样的状态管理器。

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

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 2021-06-27
      • 2021-07-19
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      相关资源
      最近更新 更多