反应钩子“useEffect"有条件地调用 [英] React Hook "useEffect" is called conditionally

查看:65
本文介绍了反应钩子“useEffect"有条件地调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React 抱怨下面的代码,说它 useEffect 被有条件地调用:

React is complaining about code below, saying it useEffect is being called conditionally:

import React, { useEffect, useState } from 'react'
import VerifiedUserOutlined from '@material-ui/icons/VerifiedUserOutlined'
import withStyles from '@material-ui/core/styles/withStyles'
import firebase from '../firebase'
import { withRouter } from 'react-router-dom'

function Dashboard(props) {
  const { classes } = props
  
  const [quote, setQuote] = useState('')

	if(!firebase.getCurrentUsername()) {
		// not logged in
		alert('Please login first')
		props.history.replace('/login')
		return null
	}

	useEffect(() => {
		firebase.getCurrentUserQuote().then(setQuote)
	})

	return (
		<main>
			// some code here
		</main>
	)

	async function logout() {
		await firebase.logout()
		props.history.push('/')
	}
}

export default withRouter(withStyles(styles)(Dashboard))

然后返回错误:

  Line 48:  React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks

有人碰巧知道这里的问题是什么吗?

Does anyone happen to know what the problem here is?

推荐答案

你的代码,在包含 returnif 语句之后,相当于一个 else 分支:

Your code, after an if statement that contains return, is equivalent to an else branch:

if(!firebase.getCurrentUsername()) {
    ...
    return null
} else {
    useEffect(...)
    ...
}

这意味着它是有条件地执行的(仅当 return 未执行时).

Which means that it's executed conditionally (only when the return is NOT executed).

修复:

useEffect(() => {
  if(firebase.getCurrentUsername()) {
    firebase.getCurrentUserQuote().then(setQuote)
  }
}, [firebase.getCurrentUsername(), firebase.getCurrentUserQuote()])

if(!firebase.getCurrentUsername()) {
  ...
  return null
}

这篇关于反应钩子“useEffect"有条件地调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆