我从 React 得到一个错误:超过最大更新深度
Posted
技术标签:
【中文标题】我从 React 得到一个错误:超过最大更新深度【英文标题】:I get an Error from React: Maximum update depth exceeded 【发布时间】:2021-03-01 21:59:31 【问题描述】:我写了我的代码,我认为一切都是正确的,但是我从 react.js 得到一个错误 错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
App.js:
import React, Component from 'react';
import Navbar from "./component/Navbar";
import './App.css';
import Users from './component/Users';
class App extends Component
state =
users: [
id: 1,
name: "Jessie Alby",
salary: "5000",
department: "Software"
,
id: 2,
name: "John Tyson",
salary: "10000",
department: "Engineer"
,
id: 3,
name: "Billie Ashley",
salary: "6000",
department: "Doctor"
]
deleteUser =(id) =>
this.setState(
users: this.state.users.filter(user => id !== user.id)
)
render()
return (
<div className="container">
<Navbar title='User App2'/>
<hr/>
<Users deleteUser=this.deleteUser() users=this.state.users/>
</div>
);
export default App;
用户.js
import React, Component from 'react'
import PropTypes from 'prop-types'
class User extends Component
state =
isVisible : false
static defaultProps =
name: "No info",
salary: "No info",
department: "No info"
onClickEvent= (e) =>
this.setState(
isVisible: !this.state.isVisible
)
onDeleteUser = (e) =>
const id,deleteUser = this.props;
deleteUser(id);
render()
//Destructing
const name,department,salary = this.props;
const isVisible = this.state;
return (
<div className="col-md-8 mb-4">
<div className="card">
<div className="card-header d-flex justify-content-between" style=cursor:"pointer">
<h4 className="d-inline" onClick=this.onClickEvent.bind(this)>name</h4>
<i onClick=this.onDeleteUser className="far fa-trash-alt" style=cursor:"pointer"></i>
</div>
isVisible ? <div className="card-body">
<p className="card-text">Salary: salary</p>
<p className="card-text">Department: department</p>
</div> : null
</div>
</div>
)
User.propTypes =
name: PropTypes.string.isRequired,
salary: PropTypes.string.isRequired,
department: PropTypes.string.isRequired,
deleteUser: PropTypes.func.isRequired
export default User;
Users.js
import React, Component from 'react';
import User from "./User";
import PropTypes from 'prop-types';
class Users extends Component
render()
const users,deleteUser = this.props;
return (
<div>
users.map(user=>
return(
<User
key=user.id
id=user.id
name=user.name
salary=user.salary
department=user.department
deleteUser=deleteUser
/>
)
)
</div>
)
Users.propTypes =
users: PropTypes.array.isRequired,
deleteUser: PropTypes.func.isRequired
export default Users;
【问题讨论】:
【参考方案1】:这可能与此有关:
<Users deleteUser=this.deleteUser() users=this.state.users/>
当您将()
放在函数末尾时,您所做的是调用它(执行它)。当你想通过它时,你必须这样做:
<Users deleteUser=this.deleteUser users=this.state.users/>
【讨论】:
很高兴我能帮上忙。如果答案对您有帮助,请将其标记为已接受答案,以便更多人从中受益。 我标记了,但堆栈说您可以在 4 分钟内接受答案。我会在 4 分钟后标记这个,再次感谢你以上是关于我从 React 得到一个错误:超过最大更新深度的主要内容,如果未能解决你的问题,请参考以下文章