太多的重新渲染,无限的重新渲染

时间:2021-05-07 22:17:45

标签: reactjs

当我从父组件 (Post) 使用 setPost 调用 usePost hook 时,为什么这会导致无限重新渲染?导致错误的原因是什么?

function Post({ activePostId }) {
  const { status, post, setPost, error, refetch } = usePost(activePostId)
  const [savePost, savePostStatus] = useSavePost()

  setPost('SetPost')

  const onSubmit = async (values) => {
    try {
      await savePost(values)
      refetch()
    } catch (err) {
      console.error(err)
    }
  }
export default function usePost(postId) {
  const [post, setPost] = React.useState()
  const [error, setError] = React.useState()
  const [status, setStatus] = React.useState('loading')

  const refetch = async () => {
    try {
      setStatus('loading')

      const post = await axios
        .get(`/api/posts/${postId}`)
        .then((res) => res.data)

      setPost(post)
      setError()
      setStatus('success')
    } catch (err) {
      setError(err)
      setStatus('error')
    }
  }

  React.useEffect(() => {
    refetch()
  }, [])

  return {
    post,
    setPost,
    status,
    error,
    refetch,
  }
}

1 个答案:

答案 0 :(得分:0)

setPost 更改您的钩子中的 post 值,该值由您的组件使用。这会触发重新渲染,从而导致无限循环。

要解决此问题,您可能只希望调用 setPost 的次数有限。您可以通过使用 useEffect 仅在启动时调用它来修复您的示例。

function Post({ activePostId }) {
  const { status, post, setPost, error, refetch } = usePost(activePostId)
  const [savePost, savePostStatus] = useSavePost()

  useEffect(() => {
    setPost('SetPost')
  }, []); // <- the empty array here ensures that the setPost is called once, if you want it called on other dependency changes, you can add them here.
  
  const onSubmit = async (values) => {
    try {
      await savePost(values)
      refetch()
    } catch (err) {
      console.error(err)
    }
  }

相关问题