动态更改反应模态数据

Change react-modal data dynamically

我有一个父组件 App.js 和一个子组件 MealModal.js。当用户点击特定的餐卡时,它会弹出一个模式,显示有关该餐的更多信息。

因此我尝试找到一种方法来动态更改模态的数据,具体取决于单击的餐卡

我试过将饭菜的id传给onClick={this.openModal}函数,设置modalId的状态就是函数。但是我收到以下错误:

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

到目前为止,这是我的组件:

App.js:

import React from 'react';

import MealCard from './MealCard';
import MealsMap from './MealsMap';
import MealsFilters from './MealsFilters';
import MealModal from './MealModal';


export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      modalIsOpen: false,
      modalId: 0
    }
    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);

  };

  openModal() {
    this.setState({modalIsOpen: true});
  };

  closeModal() {
    this.setState({modalIsOpen: false});
  };

  render() {
    return (
      <div>
        <MealsFilters/>
        <div className="app-wrapper" style={{display: 'flex'}}>
          <div className="container">
            <div className="row">
              {[...Array(20)].map((x, i) =>
                  <div className="col-sm-6 col-xs-12 " key={i} onClick={this.openModal}>
                    <MealCard />
                  </div>
                )}
          </div>
        </div>
        <MealsMap/>
      </div>
      <MealModal modalIsOpen={this.state.modalIsOpen} closeModal={this.closeModal} modalId={this.state.modalId}/>
    </div>
    );
  }
}

MealModal.js

import React from 'react';
import Modal from 'react-modal';

const customStyles = {
  content : {
  }
};

Modal.setAppElement('#app')

export default class MealModal extends React.Component {
  constructor(props) {
    super(props);
  }


  render() {
    return (
      <Modal
        isOpen={this.props.modalIsOpen}
        onRequestClose={this.props.closeModal}
        style={customStyles}
        contentLabel="Meal Modal"
      >
        <div className="modal-wrapper">
          <div className="container text-center">
            <h1>Hello</h1>
            <h2>ID of this modal is {this.props.modalId}</h2>
            <h3>This is an awesome modal.</h3>
            <button onClick={this.props.closeModal}>close</button>
          </div>
        </div>
      </Modal>
    )
  }
}

知道我该怎么做吗?

好的,所以我找到了解决方案:

首先,我将父组件中的 onClick={this.openModal} 更改为 onClick= () => {this.openModal}

其次,我将id添加为参数: onClick= () => {this.openModal(i)}

最后:更新 openModal 函数:

  openModal(modalId) {
    this.setState({modalIsOpen: true,
                   modalId});
  };

并且有效。

openModal(modalId) {
    this.setState({
       modalId,
       modalIsOpen: true
    });
  };

并将调用函数修改为

 <div className="col-sm-6 col-xs-12" key={i} onClick={() => this.openModal(x) } >
    <MealCard/>      
 </div>