【问题标题】:Rendered fewer react hooks than expected渲染的反应钩子比预期的要少
【发布时间】:2021-07-17 04:45:43
【问题描述】:

我要疯了,试图理解为什么我不断收到这个错误:

它看起来像我的 setShowCreatePostModal 但不管我如何安排那个钩子或者它是如何通过道具传递的,我仍然得到一个错误。

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

我用上面的钩子关闭模态框后弹出错误。我错过了什么?

提前谢谢你!

【问题讨论】:

  • 你也可以分享你的CreatePostModal 组件吗?
  • 什么是usePostuseMoment 函数?它们听起来像自定义钩子,是吗?
  • @hexbioc 我同意,但我认为 linter 也会抱怨它们被有条件地调用。我想这意味着 OP 没有在启用 react-hook 规则的情况下运行 linter。
  • usePostuseMoment 指向一个基本上是钩子的函数 - SWR

标签: reactjs react-hooks


【解决方案1】:

在每个渲染中应该有相同数量的钩子调用。在您的情况下,您有条件地致电useMomentusePost。所有挂钩调用必须在top level of the component。从条件语句中删除自定义钩子的调用,它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2021-10-03
    • 1970-01-01
    • 2021-08-23
    • 2021-07-19
    • 1970-01-01
    • 2020-08-16
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多