1

我试图在表格上有一个编辑按钮,单击该按钮时,将拉出一个表单页面并使用单击编辑按钮的表格行中的信息预填充表单。

我正在使用路由器 dom 链接到表单页面,但我不确定如何将数据从表格页面发送到表单页面。

这是表格代码的顶部

import React from "react";
import "./PtTable.css";
import { Link } from "react-router-dom";

class PtTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      patients: null
    };


  getPatients() {
    fetch("https://localhost:5001/api/PtSearchPg")
      .then(response => response.json())
      .then(data => this.setState({ patients: data }));
  }

这是编辑按钮。正上方是数据库中的患者地图。

              {this.state.patients.map(patient => (
                <tr key={patient.patientId}>
                  <td>{patient.firstName}</td>
                  <td>{patient.lastName}</td>
                  <td>{patient.dob}</td>
                  <td>{patient.unitId}</td>
                  <td align="center">
                    <Link to="/PtEditPg">
                      <button
                        type="button"
                        className="btn btn-sm btn-warning btnspace"
                      >
                        Edit
                      </button>
                    </Link>

这是编辑表单的顶部。我在 ptId 和 firstName 上尝试了几种方法,但没有成功。firstName 表示未定义。

import React from "react";
import "./PtForm.css";

class PtEditForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      ptId: props.ptId,
      firstName: props.patient.firstName,
      lastName: null,
      dob: null,
      address: null,
      address2: null,
      city: null,
      state: null,
      zipCode: null,
      account: null,
      medRecord: null,
      unitId: null,
      states: null
    };
4

1 回答 1

0

您可以将这些值添加到搜索查询

 <Link to={`/PtEditPg?firstName=${patient.firstName}&lastName=${patient.lastName}&dob=${patient.dob}&unitId=${patient.unitId}`}>
  <button
    type="button"
    className="btn btn-sm btn-warning btnspace"
  >
    Edit
  </button>
</Link>

然后使用 withRouter 和一些函数在组件上读取查询值,我总是使用查询字符串解析方法

...
import { withRouter } from 'react-router-dom';
import * as qs from 'query-string';

class PtEditForm extends React.Component {
  constructor(props) {
    super(props);

    const { location } = this.props;
    const { search } = location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });

    this.state = {
      ptId: query.ptId || null,
      firstName: query.firstName || null,
      lastName: query.lastName || null,
      dob: query.dob || null,
      address: null,
      address2: null,
      city: null,
      state: null,
      zipCode: null,
      account: null,
      medRecord: null,
      unitId: query.unitId || null,
      states: null
    };
...

export default withRouter(PtEditForm);

于 2019-07-23T03:16:38.703 回答