开发者问题收集

渲染的反应钩子数量比预期少

2021-04-22
486

我快要疯了,想弄明白为什么我总是收到这个错误: enter image description here

看起来好像是我的 setShowCreatePostModal 出了问题,但不管我如何安排那个钩子,或者它是如何通过 prop 传递的,我仍然会收到错误。

const PostsFeedContainer: FunctionComponent<PostsFeedContainerProps> = ({
  loggedInUserImageUrl,
  posts,
  onMutatePosts,
  checkedIn,
  profile,
  handleCollection,
  momentId,
}: PostsFeedContainerProps) => {
  const [filteredPosts, setFilteredPosts] = useState(posts)
  const [momentsList, setMoments] = useState([])
  const [showCreatePostModal, setShowCreatePostModal] = useState<boolean>(false)
  const { updateStore } = useContext(AppContext)
  const { moments } = useMoments()
  const router = useRouter()

  useEffect(() => {
    if (moments?.length) {
      setMoments(moments)
    }

  }, [moments])

  let nextPosts = [];
  if (posts.length != 0 && posts.length % 10 === 0) {
    let next
    if (router.pathname === "/") {
      next = filteredPosts.length && usePost(filteredPosts[filteredPosts.length - 1].id, {}, true)
    } else {
      next = filteredPosts.length && useMoment(momentId, {}, true, 10, filteredPosts[filteredPosts.length - 1].id)
    }
    const { data: nextPost } = next
    nextPosts = nextPost
  }

  const handleModalOpen = () => {
    if (!profile) {
      updateStore({ isAlertLoginModalOpen: true })
      return
    }
    if (!checkedIn) {
      toast("Please check in to the moment.", toastProps)
    } else {
      setShowCreatePostModal(true)
    }
  }

  const handleModalClose = () => {
    // if (onMutatePosts) onMutatePosts()

    if (showCreatePostModal) {
      setShowCreatePostModal(false)
    }
  }

  const fetchNextTen = () => {
    setFilteredPosts(filteredPosts.concat(nextPosts))
  }

  const handleDelete = (id) => {
    const filtPosts = filteredPosts.filter((item) => item.id !== id)
    setFilteredPosts(filtPosts)
  }

  const handleAdd = async (p) => {
    await filteredPosts.unshift(p)
    handleModalClose();
  }

  return (
    <>
      <CreatePostModal showModal={showCreatePostModal} handleAdd={handleAdd} />
      <Container container item>
        <SCard>
          <SCardContent p={0} m={0}>
            <InputArea
              isHeader
              placeholder="Start a post"
              userImage={loggedInUserImageUrl}
              inputDescription="Share tips, stories, questions and even overshares that you're going through"
              onClick={handleModalOpen}
              disabled={!checkedIn}
              p="sm"
              pt="md"
              pb="md"
            />
            <TrendingTags isPeach smOnly />
            <SGrid container item mt={50} align="center" justify="center" direction="row">
              {posts.length ? (
                filteredPosts.map((post) => (
                  <PostCard
                    handleDelete={handleDelete}
                    key={post.id}
                    {...post}
                    likesCount={post.likesCount}
                    liked={post.liked}
                    loggedInUser={{
                      userImageUrl: loggedInUserImageUrl,
                      userImageAlt: "",
                    }}
                    moment={momentsList.find((m) => m.id === post.momentId)}
                    linkable
                    handleCollection={handleCollection}
                  />
                ))
              ) : (
                <Text align="center" small pb="md">
                  Sorry, no results found
                </Text>
              )}
            </SGrid>
            {nextPosts && nextPosts.length >= 1 ? (
              <LoadMoreDiv onClick={() => fetchNextTen()}>
                LOAD MORE <KeyboardArrowDownIcon />
              </LoadMoreDiv>
            ) : null}
          </SCardContent>
        </SCard>
      </Container>
    </>
  )
}

export default PostsFeedContainer

使用上面的钩子关闭模式后,错误弹出。我遗漏了什么?

提前谢谢您!

1个回答

每次渲染时,应该有相同数量的钩子调用。在您的情形下,您正在有条件地调用 useMomentusePost 。所有钩子调用都必须位于 组件的顶层 。从您的条件语句中删除自定义钩子的调用,它应该可以正常工作。

Medi
2021-04-23