为了账号安全,请及时绑定邮箱和手机立即绑定

在 ReactJS 的基于类的组件中使用两个组件

在 ReactJS 的基于类的组件中使用两个组件

潇潇雨雨 2022-12-09 14:00:19
我正在尝试使用两个基于类的组件<Cities>和<Hospital>另一个组件。我收到一个错误:-超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。React 限制嵌套更新的数量以防止无限循环。我正在尝试创建 4 个按钮,这些按钮将显示那些带有单击按钮的城市的医院。import React,{ Component } from 'react';import Hospital from './hospital/hospital'import Cities from '../sidebarcomp/cities'class Hospitals extends Component {state = {    hospitals: [      { id: 1, status: false, name: 'Apollo Hospital', city: 'Chennai', bedtype1: 500, bedtype2: 800, bedtype3: 1300,bed1av: 60, bed2av: 40, bed3av: 20, },      { id: 2, status:false, name: 'Fortis Hospital', city: 'New Delhi', bedtype1: 600, bedtype2: 1000, bedtype3: 1400, bed1av: 60, bed2av: 40, bed3av: 20,  },      { id: 3, status: true, name: 'Tata Memorial Hospital', city: 'Mumbai', bedtype1: 400, bedtype2: 800, bedtype3: 1200, bed1av: 60, bed2av: 40, bed3av: 20,  },      { id: 4, status: true,name: 'Lilavati Hospital', city: 'Pune', bedtype1: 500, bedtype2: 900, bedtype3: 1300, bed1av: 60, bed2av: 40, bed3av: 20,  }    ],};render() {    return(      <React.Fragment>        <Cities         hospitals={this.state.hospitals}        />         {this.state.hospitals.map((hospital, index) => {        if(hospital.status){        return (        <Hospital          name={hospital.name}          bed1av={hospital.bed1av}          bed2av={hospital.bed2av}          bed3av={hospital.bed3av}          key={hospital.id}        />      )};        })}        </React.Fragment>    )}}export default Hospitals;
查看完整描述

3 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

问题是您正在调用组件setState内部的函数Cities。


您应该做的是将nameChangedHandler作为道具传递给城市组件,以便它更新父组件(医院)的状态


class Hospitals extends Component {

    nameChangeHandler = (id) => {

        ....

    }

    ...

    <Cities nameChangedHandler={this.nameChangedHandler}/> 


在 Cities.js 中


class Cities extends Component {

   // remove nameChangeHandlerFunction


   render(){

    return(

      <div>

        <button onClick={this.props.nameChangedHandler(1)}>Chennai</button>

        <button onClick={this.props.nameChangedHandler(3)}>Mumbai</button>

        <button onClick={this.props.nameChangedHandler(4)}>Pune</button>

        <button onClick={this.props.nameChangedHandler(2)}>New Delhi</button>

      </div>

      )

    }


查看完整回答
反对 回复 2022-12-09
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

您必须使用如下处理程序:

nameChangedHandler = (id) => () => {


查看完整回答
反对 回复 2022-12-09
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

我想这可能是因为你在渲染中有 console.log 这样的。如果你真的需要它,我建议你把它放在回报中。



查看完整回答
反对 回复 2022-12-09
  • 3 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信