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

我正在尝试使用两个基于类的组件<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;


潇潇雨雨
浏览 171回答 3
3回答

UYOU

问题是您正在调用组件setState内部的函数Cities。您应该做的是将nameChangedHandler作为道具传递给城市组件,以便它更新父组件(医院)的状态class Hospitals extends Component {&nbsp; &nbsp; nameChangeHandler = (id) => {&nbsp; &nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; }&nbsp; &nbsp; ...&nbsp; &nbsp; <Cities nameChangedHandler={this.nameChangedHandler}/>&nbsp;在 Cities.js 中class Cities extends Component {&nbsp; &nbsp;// remove nameChangeHandlerFunction&nbsp; &nbsp;render(){&nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.props.nameChangedHandler(1)}>Chennai</button>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.props.nameChangedHandler(3)}>Mumbai</button>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.props.nameChangedHandler(4)}>Pune</button>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.props.nameChangedHandler(2)}>New Delhi</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }

天涯尽头无女友

您必须使用如下处理程序:nameChangedHandler = (id) => () => {

一只斗牛犬

我想这可能是因为你在渲染中有 console.log 这样的。如果你真的需要它,我建议你把它放在回报中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript