javascript - React Hook "useEffect"有条件地被调用

标签 javascript reactjs react-hooks

React 提示下面的代码,说它有条件地调用 useEffect:

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))

这会返回错误:

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render.

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

最佳答案

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

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

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

修复:

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

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

关于javascript - React Hook "useEffect"有条件地被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57620799/

相关文章:

javascript - window.localStorage.setItem 未在 onkeydown 回调中执行

javascript - 在 iOS Safari 中缩放图像并将其绘制到 Canvas 时,宽度正确但高度被压缩

reactjs - React-navigation:导航到相同的 RouteName 但具有不同的参数

android - React native expo - 响应超时

reactjs - Material-ui:用省略号在 2 行中写入文本

javascript - 在 Material UI 菜单组件中处理点击事件时出现问题

javascript - 如何修复 React 自定义钩子(Hook)中的 'Hooks can only be called inside the body of a function component' 错误?

reactjs - 如何在移动到下一个屏幕之前等待 React useEffect Hook 完成

javascript - DataTables 无法在 Laravel Blade 模板中工作

Javascript 将文本和背景的颜色更改为输入值