【问题标题】:How do I make my post load only if it has been fetched仅当已获取帖子时,如何使帖子加载
【发布时间】:2021-01-12 13:56:32
【问题描述】:

每次我打开一个新的帖子页面时,上一篇帖子的数据都会在屏幕上显示几毫秒,然后显示新数据。 我试图检查帖子是否正在加载并使用 setIsLoading 函数将其设置为状态,但它不起作用。 请看下面的代码:

const PostPage = ({post, setPost, isLoading, setIsLoading}) => {
  const location = useLocation()
  const pathname = location.pathname.split("/")[2]

  useEffect(() => {
    setIsLoading(true)
    const fetchData = async () => {
      let res = await axios.get(`http://localhost:4000/posts/${pathname}`)
      const postData = res.data
      setPost(postData)
      setIsLoading(false)
    }
    fetchData()
  }, [])

  return (
    <>
      {!isLoading && (
        <div>
          <h1>{post.title}</h1>
          <p>{post.text}</p>
        </div>
      )}
    </>
  )
}

这些是我的路线:

<Switch>
          <Route path="/" exact>
            {isLogged && (
              <AddPost
                posts={posts}
                setPosts={setPosts}
                postTitle={postTitle}
                setPostTitle={setPostTitle}
                postText={postText}
                setPostText={setPostText}
                setIsLoading={setIsLoading}
              />
            )}
            <div className="posts-row">
              {posts.slice(0).reverse().map(post => (
                <Post
                  key={post.id}
                  id={post.id}
                  postTitle={post.title}
                  postText={post.text}
                  isLogged={isLogged}
                  posts={posts}
                  setPosts={setPosts}
                  />
              ))}
            </div>
          </Route>
          <Route path="/posts/:id" exact>
            <PostPage
              post={post}
              setPost={setPost}
              isLoading={isLoading}
              setIsLoading={setIsLoading}
            />
          </Route>
        </Switch>

在 App.js 中,我将 isLoading 设置为 true,但它仅适用于第一篇文章。 为了 React,请不要报告我的问题:D

编辑: Post.js

const Post = ({postTitle, postText, isLogged, posts, setPosts, id}) => {

  const removePost = async (id) => {
    const postArray = posts.filter((post) => (post.id !== id))
    let res = await axios.delete(`http://localhost:4000/posts/${id}`)
    setPosts(postArray)
  }

  return (
    <div className="post">
      <Link to={`/posts/${id}`}>
        <strong>
          {postTitle}
        </strong>
      </Link>
      <p>{postText}</p>
      {isLogged && (
        <button onClick={() => removePost(id)}>
          ????️
        </button>
      )}
    </div>
  )
}

【问题讨论】:

  • 请显示您的路线
  • 我编辑了原帖

标签: reactjs ecmascript-6


【解决方案1】:

您的效果挂钩仅在组件首次挂载时运行。如果您想在每次pathname 更改时运行它,请将其添加到其依赖数组中:

useEffect(() => {
  setIsLoading(true)
  const fetchData = async () => {
    let res = await axios.get(`http://localhost:4000/posts/${pathname}`)
    const postData = res.data
    setPost(postData)
    setIsLoading(false)
  }
  fetchData()
}, [pathname])

【讨论】:

    【解决方案2】:

    您需要将setIsLoading 放入fetchData 函数中: 并将pathname 添加到useEffect 依赖项并检查pathname 是否具有价值:

    const fetchData = async () => {
      setIsLoading(true);
      let res = await axios.get(`http://localhost:4000/posts/${pathname}`);
      const postData = res.data;
      setPost(postData);
      setIsLoading(false);
    };
    
    useEffect(() => {
      if (pathname) {
        fetchData();
      }
    }, [pathname]);
    
    

    EDIT: 所以这是你需要做的:

    import { useParams } from "react-router-dom";
    
    const PostPage = ({ post, setPost, isLoading, setIsLoading }) => {
      const { id } = useParams();
    
      const fetchData = async () => {
        setIsLoading(true);
        let res = await axios.get(`http://localhost:4000/posts/${id}`);
        const postData = res.data;
        setPost(postData);
        setIsLoading(false);
      };
    
      useEffect(() => {
        if (id) {
          fetchData();
        }
      }, [id]);
    
      return (
        <>
          {!isLoading && (
            <div>
              <h1>{post.title}</h1>
              <p>{post.text}</p>
            </div>
          )}
        </>
      );
    };
    

    【讨论】:

    • @VadimSurugiu 你的意思是什么不起作用。在这些更改之后,问题不在您的 PostPage 组件中。创建一个代码沙箱,这样我就可以看到你正在尝试做的事情的全貌codesandbox.io
    • 我做不到,我从本地 api 获取数据
    • 什么不起作用?你期待发生什么?相反会发生什么?细节,细节,细节。
    • 当我转到一个新帖子时,它会在几毫秒内显示旧帖子的标题和文本,然后它会更新,我不希望这种情况发生
    • 我已经从 post.js 中添加了指向帖子页面链接的代码,也许这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2021-12-15
    • 2021-08-04
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多