#javascript #json #reactjs #.net-core #rendering
Вопрос:
У меня есть форма создания/редактирования в react следующим образом:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';
interface AddEmployeeDataState {
title: string;
loading: boolean;
error: string;
cityList: Array<any>;
nationalityList: Array<any>;
genderList: Array<any>;
roleList: Array<any>;
losList: Array<any>;
designationList: Array<any>;
religionList: Array<any>;
empData: EmployeeData;
}
export class EmployeeDetails extends React.Component<RouteComponentProps<{}>, AddEmployeeDataState> {
constructor(props) {
super(props);
this.state = {
title: "",
loading: false,
error: "",
empData: new EmployeeData(),
cityList: [],
nationalityList: [],
genderList: [],
roleList: [],
losList: [],
designationList: [],
religionList: []
};
fetch('api/Employee/GetCities')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ cityList: data });
});
fetch('api/Employee/GetNatonalities')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ nationalityList: data });
});
fetch('api/Employee/GetRoles')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ roleList: data });
});
fetch('api/Employee/GetLOS')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ losList: data });
});
fetch('api/Employee/GetDesignations')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ designationList: data });
});
fetch('api/Employee/GetGenders')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ genderList: data });
});
fetch('api/Employee/GetReligions')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ religionList: data });
});
this.handleSave = this.handleSave.bind(this);
}
componentDidMount() {
var empid = this.props.match.params["empid"];
if (empid > 0) {
fetch('api/Employee/Details/' empid)
.then(response => response.json())
.then(data => {
this.setState({
title: "Edit",
loading: false,
empData: data
});
console.log("data:");
console.log(data);
});
console.log("empData:");
console.log(this.state.empData);
}
else {
this.state = {
title: "Create",
loading: false,
error: "",
empData: new EmployeeData(),
cityList: [],
nationalityList: [],
genderList: [],
roleList: [],
losList: [],
designationList: [],
religionList: []
};
}
}
public render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderCreateForm(
this.state.cityList,
this.state.nationalityList,
this.state.genderList,
this.state.roleList,
this.state.losList,
this.state.designationList,
this.state.religionList
);
return <div>
<h1>{this.state.title}</h1>
<h3>Employee</h3>
<hr />
{contents}
</div>;
}
private handleSave(event) {
event.preventDefault();
fetch('api/Employee/Save', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(this.state.empData),
}).then((response) => response.json())
.then(data => {
this.setState({ error: data.message });
if (data.success) {
this.props.history.push("/Employee/AllEmployees");
}
}).catch(err => {
console.error(err);
})
}
private renderCreateForm(
cityList: Array<any>,
nationalityList: Array<any>,
genderList: Array<any>,
roleList: Array<any>,
losList: Array<any>,
designationList: Array<any>,
religionList: Array<any>
) {
return (
<form onSubmit={this.handleSave} >
<div className="form-group row" >
<input type="hidden" name="FldId" value={this.state.empData.fldId} />
</div>
< div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="fldEmpCode">
Employee Code
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldEmpCode"
defaultValue={this.state.empData.fldEmpCode}
onChange={e => this.state.empData.FldEmpCode = e.target.value}
required
/>
</div>
</div >
< div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="fldName">
Name
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldName"
defaultValue={this.state.empData.fldName}
onChange={e => this.state.empData.FldName = e.target.value}
required
/>
</div>
</div >
< div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="fldFatherName">
Father Name
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldFatherName"
defaultValue={this.state.empData.fldFatherName}
onChange={e => this.state.empData.FldFatherName = e.target.value}
required
/>
</div>
</div >
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldGender">
Gender
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldGender"
defaultValue={this.state.empData.fldGender}
onChange={e => this.state.empData.FldGender = Number(e.target.value)}
required
>
<option value="">-- Select Gender --</option>
{genderList.map(gender =>
<option key={gender.fldId} value={gender.fldId}>
{gender.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldReligion">
Religion
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldReligion"
defaultValue={this.state.empData.fldReligion}
onChange={e => this.state.empData.FldReligion = Number(e.target.value)}
required
>
<option value="">-- Select Religion --</option>
{religionList.map(religion =>
<option key={religion.fldId} value={religion.fldId}>
{religion.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldCnic">
CNIC
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldCnic"
defaultValue={this.state.empData.fldCnic}
onChange={e => this.state.empData.FldCnic = e.target.value}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldDob">
Date of Birth
</label>
<div className="col-md-4">
<input
className="form-control"
type="date"
name="fldDob"
defaultValue={
this.state.empData.fldDob == null ?
new Date().toISOString().substring(0, 10) :
this.state.empData.FldDob.toISOString().substring(0, 10)
}
onChange={e => this.state.empData.FldDob = new Date(e.target.value)}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldCity">
City
</label>
<div className="col-md-4">
<select
lassName="form-control"
data-val="true"
name="fldCity"
defaultValue={this.state.empData.fldCity}
onChange={e => this.state.empData.FldCity = Number(e.target.value)}
required
>
<option value="">-- Select City --</option>
{cityList.map(city =>
<option key={city.fldId} value={city.fldId}>
{city.fldName}
</option>
)}
</select>
</div>
</div >
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldPermanentAddress">
Permanent Address
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldPermanentAddress"
defaultValue={this.state.empData.fldPermanentAddress}
onChange={e => this.state.empData.FldPermanentAddress = e.target.value}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldContactNumber">
Contact Number
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldContactNumber"
defaultValue={this.state.empData.fldContactNumber}
onChange={e => this.state.empData.FldContactNumber = e.target.value}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldNationality">
Nationality
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldNationality"
defaultValue={this.state.empData.fldNationality}
onChange={e => this.state.empData.FldNationality = Number(e.target.value)}
required
>
<option value="">-- Select Nationality --</option>
{nationalityList.map(nationality =>
<option key={nationality.fldId} value={nationality.fldId}>
{nationality.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldEmailId">
Email ID
</label>
<div className="col-md-4">
<input
className="form-control"
type="email"
name="fldEmailId"
defaultValue={this.state.empData.fldEmailId}
onChange={e => this.state.empData.FldEmailId = e.target.value}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldDateOfJoining">
Date of Joining
</label>
<div className="col-md-4">
<input
className="form-control"
type="date"
name="fldDateOfJoining"
defaultValue={
this.state.empData.fldDateOfJoining == null ?
new Date().toISOString().substring(0, 10) :
this.state.empData.FldDateOfJoining.toISOString().substring(0, 10)
}
onChange={e => this.state.empData.FldDateOfJoining = new Date(e.target.value)}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldRole">
Role
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldRole"
defaultValue={this.state.empData.fldRole}
onChange={e => this.state.empData.FldRole = Number(e.target.value)}
required
>
<option value="">-- Select Role --</option>
{roleList.map(role =>
<option key={role.fldId} value={role.fldId}>
{role.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldLos">
LOS
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldLos"
defaultValue={this.state.empData.fldLos}
onChange={e => this.state.empData.FldLos = Number(e.target.value)}
required
>
<option value="">-- Select LOS --</option>
{losList.map(los =>
<option key={los.fldId} value={los.fldId}>
{los.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldOfficeLocation">
Office Location
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldOfficeLocation"
defaultValue={this.state.empData.fldOfficeLocation}
onChange={e => this.state.empData.FldOfficeLocation = Number(e.target.value)}
required
>
<option value="">-- Select Location --</option>
{cityList.map(city =>
<option key={city.fldId} value={city.fldId}>
{city.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldDesignation">
Designation
</label>
<div className="col-md-4">
<select
className="form-control"
data-val="true"
name="fldDesignation"
defaultValue={this.state.empData.fldDesignation}
onChange={e => this.state.empData.FldDesignation = Number(e.target.value)}
required
>
<option value="">-- Select Designation --</option>
{designationList.map(designation =>
<option key={designation.fldId} value={designation.fldId}>
{designation.fldName}
</option>
)}
</select>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldUsername">
Username
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="fldUsername"
defaultValue={this.state.empData.fldUsername}
onChange={e => this.state.empData.FldUsername = e.target.value}
required
/>
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="fldPassword">
Password
</label>
<div className="col-md-4">
<input
className="form-control"
type="password"
name="fldPassword"
defaultValue={this.state.empData.fldPassword}
onChange={e => this.state.empData.FldPassword = e.target.value}
required
/>
</div>
</div>
<div>{this.state.error}</div>
<div className="form-group">
<button type="submit" className="btn btn-default">Save</button>
</div >
</form >
)
}
}
export class EmployeeData {
FldId: number = 0;
FldEmpCode: string = "";
FldName: string = "";
FldFatherName: string = "";
FldGender: number = 0;
FldReligion: number = 0;
FldCnic: string = "";
FldDob: Date = new Date;
FldCity: number = 0;
FldPermanentAddress: string = "";
FldContactNumber: string = "";
FldNationality: number = 0;
FldEmailId: string = "";
FldStatus: boolean = false;
FldDateOfJoining: Date = new Date;
FldRole: number = 0;
FldLos: number = 0;
FldOfficeLocation: number = 0;
FldCreatedAt: Date = new Date;
FldCreatedBy: number = 0;
FldUpdatedAt: Date = new Date;
FldUpdatedBy: number = 0;
FldDesignation: number = 0;
FldUsername: string = "";
FldPassword: string = "";
FldResignDate: Date = new Date;
}
Создать форму работает нормально. Но при открытии формы для редактирования текстовое поле и выпадающие списки не заполняются. В ComponentDidMount()
, console.log("empData:");
сначала печатается, что дает пустую модель, затем console.log("data:");
вызывается, которая заполняется данными.
Кроме того, форма отображается 2 раза сначала для создания, а затем для редактирования. Я не могу понять, что я делаю не так?