我正在尝试实现登录视图,但是不断出现错误:
已超过最大更新深度。当一个组件发生这种情况 重复调用componentWillUpdate内的setState或 componentDidUpdate。 React将嵌套更新的数量限制为 防止无限循环。
当点击提交按钮时。
import './LoginView.css'
import React, { useState } from 'react'
import { Button, TextField, CircularProgress } from '@material-ui/core'
import Auth from '../../utils/Auth'
import { Redirect } from 'react-router-dom'
import Network from '../../utils/Network'
import Toast, { IToastData, ToastType } from '../Toast/Toast'
import AdManager from '../../utils/AdManager'
import pkg from '../../../package.json'
import Logo from "../../assets/logo.png"
export default function LoginView() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [toastData, setToastData] = useState<IToastData | undefined>(undefined)
const onSubmit = async () => {
try {
setIsLoading(true)
await Network.instance.login(username, password)
const success = Auth.instance.isLoggedIn()
if (success) {
await AdManager.instance.start()
}
} catch (error) {
setToastData({
type: ToastType.Error,
message: "Something went wrong!"
})
} finally {
setIsLoading(false) // According to react this is the culprit
}
}
const createInputFields = () => {
return (
<>
<TextField
className="textField"
label="Username"
type="email"
margin="normal"
onChange={x => setUsername(x.target.value)}
required={true}
/>
<TextField
className="textField"
label="Password"
type="password"
margin="normal"
onChange={x => setPassword(x.target.value)}
required={true}
/>
</>
)
}
if (Auth.instance.isLoggedIn()) {
const path = (AdManager.instance.sources.length === 1) ? '/' : '/selection'
return <Redirect to={path} />
}
return (
<>
<div className="root">
<img src={Logo} className="Logo" alt="Logo" />
<div className="TextFieldsContainer">
{isLoading ? <CircularProgress /> : createInputFields()}
</div>
<Button className="button" variant="contained" component="span" disabled={isLoading || (!username || !password)} onClick={onSubmit}>
Log in
</Button>
{!!toastData && <Toast open={true} message={toastData.message} type={toastData.type} />}
</div>
<div className="VersionNumber">{pkg.version}</div>
</>
)
}
答案 0 :(得分:1)
我已经解决了这个问题,而错误是由React指定的行间接调用的;真正的原因是组件中的一行代码被重定向到了。
总结。 React在其错误消息中是正确的,但不够具体,无法提供任何实际帮助。我使用git bisect发现了错误。经常提交并进行范围界定是这里的救星。