如何在React JS中将数据从一个组件访问到另一个组件

时间:2020-04-21 15:06:28

标签: reactjs react-redux react-props

嗨,我有一个组件正在渲染另一个组件。我无法将数据从Agmt组件传递到AgmtTable组件。 我想做的是将详细信息传递给AgmtTable组件,在其中形成一个表,并在父Agmt组件中显示该表。我无法理解它如何在AgmtTable中访问它。 Agmt组件中的代码如下。

import React, { Component } from "react";
import { connect } from "react-redux";
import AgmtTable from "./AgmtTable";
import * as AgmtAction from "../actions/AgmtAction";

class AgmtContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  //fetch Agmt details. This is giving me a data in mapStateToProps function below
  componentDidMount() {
    this.props.dispatch(
      AgmtAction.getAgmtsFor(id)
    );
  }

  render() {
    const data = this.props.Agmt;//here I have a data as object
    return (
      <React.Fragment>
        <div>
          <AgmtTable Data={data} />
        </div>
      </React.Fragment>
    );
  }
}

function mapStateToProps(state) {
  return {
    Agmt: state.AgmtsDetails.AgmtsData,// here I have a data
  };
}

export default connect(mapStateToProps)(AgmtContainer);

AgmtTable组件中的代码如下。

import React, { Component } from "react";

class AgmtTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  getHeaader = () => {
    console.log("details", this.state.details);//here I am not getting a data from props
    var tableHeadings = [
      "Agmt ID",
      "Start Date",
      "End Date",
    ];
    return tableHeadings.map((key) => {
      return <th key={key}> {key.toUpperCase()}</th>;
    });
  };

  getRowsData = (e) => {
    return this.props.Data.map((value) => {//in this line I am getting error
      const {
        Agmt_ID,
        Agmt_START_DATE,
        END_DATE,
      } = value;
      return (
        <tr key={Agmt_ID} className="clickable-row active">
          <td> {Agmt_ID} </td>
          <td> {Agmt_START_DATE} </td>
          <td> {END_DATE} </td>
        </tr>
      );
    });
  };

  render() {
    return (
      <div>
        <table
          id="display-table"
          className="table table-bordered table-hover table-responsive table-condensed table-striped table-sm"
        >
          <tbody>
            <tr>{this.getHeaader()}</tr>
            {this.getRowsData()}
          </tbody>
        </table>
      </div>
    );
  }
}

export default AgmtTable;

0 个答案:

没有答案