问题描述
我已经从数据库渲染了数据并显示在我创建的页面中。(它一次正确地显示了所有数据) 然后我在该类下添加了generate as pdf会话,它成功地将数据提供为pdf。但是在页面中,数据显示了两次。我希望数据仅显示一次。有人可以在我的编码中识别出错误吗?
哪个是.jsx页面
EmployeePDF.jsx
import React,{ useRef } from 'react';
import axios from 'axios';
import { useReactToPrint } from 'react-to-print';
import { render } from '@testing-library/react';
export default class EmployeePDF extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[]
}
}
componentDidMount(){
this.fetchEmpDetails();
}
fetchEmpDetails = () =>{
var url = "http://127.0.0.1:8000/EmployeeDetail-list/";
axios.get(url).then(res => {
const data = res.data;
this.setState({data});
})
};
render() {
return (
<div className="row">
<div className="col main1" style={{height:"100%"}}>
<br></br>
<h1 style={{color: "DodgerBlue",fontSize: '30px',fontWeight:"bold"}}><center>EMPLOYEE DETAILS</center></h1>
<div>
<div className="table-responsive">
<table className="table" style={{fontSize:"10px"}}>
<thead className="theadss">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Primary Phone</th>
<th>Secondary Phone</th>
<th>Position</th>
<th>Address</th>
<th>Email</th>
<th>Trained Years</th>
<th>Joined Date</th>
</tr>
</thead>
<tbody >
{this.state.data.map(user =>{
return(
<tr>
<td>{user.emp_det_id}</td>
<td>{user.employee_name}</td>
<td>{user.primary_phone}</td>
<td>{user.secondary_phone}</td>
<td>{user.position}</td>
<td>{user.address}</td>
<td>{user.email}</td>
<td>{user.trained_years}</td>
<td>{user.joined_date}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}}
//Printing or saving as PDF
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,});
return (
<div>
<EmployeePDF ref={componentRef} />
<button onClick={handlePrint}>Print or Save as PDF</button>
<br></br>
</div>
);};render(<Example/>,document.querySelector("#root"));
这是我得到的输出 我希望使用“打印或另存为pdf”按钮一次显示“员工详细信息”
(我已经使用了反应打印库)
解决方法
您可以使用ReactDom的渲染
import ReactDOM from "react-dom";
ReactDOM.render(<Example/>,document.querySelector("#root"));