В моем сценарии у меня есть два компонента ListEnterprise и AddEnterprise. При нажатии на кнопку обновления мне нужно получить доступ и отправить определенный идентификатор предприятия в AddEnterprise (мы используем тот же компонент для добавления и обновления записей). Как получить доступ к EnterpriseId в компоненте AddEnterprise? Заранее спасибо.
ListEnterprise
class ListEnterprises extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
enterprises: [],
message: null,
showFormMessage: false,
showUpdateForm: false,
}
//Any method in a react component should be bound to this
this.refreshEnterprises = this.refreshEnterprises.bind(this);
this.editEnterprise = this.editEnterprise.bind(this);
}
// After all the elements of the page is rendered correctly, this method is called.
// After the markup is set on the page, this technique called by React itself to either fetch the data from An External API or perform some unique operations which need the JSX.API
// componentDidMount() method is the perfect place, where we can call the setState() method to change the state of our application and render() the updated data loaded JSX. For example, we are going to fetch any data from an API then API call should be placed in this lifecycle method,
// and then we get the response, we can call the setState() method and render the element with updated data.
//React defines a component lifecycle. componentDidMount will be called as soon as the component is mounted. We are calling refreshCourses as soon as a component is mounted.
componentDidMount() {
this.refreshEnterprises();
}
_showMessage = (bool, update = false) => {
this.setState({
showFormMessage: bool,
showUpdateForm: false,
});
if (update) {
this.refreshEnterprises();
}
}
refreshEnterprises() {
EnterpriseService.retrieveAllEnterprises()
.then((response) => {
console.log(response.data);
this.setState({ enterprises: response.data, isLoading: false });
}).catch((error) => {
console.log(error);
});
}
// removeEnterprise(id) {
// EnterpriseService.deleteEnterprise(id)
// .then((response) => {
// console.log(response.data);
// let updatedEnterprises = [...this.state.enterprises].filter(i => i.id !== id);
// this.setState({ enterprises: updatedEnterprises });
// }).catch((error) => {
// console.log(error);
// });
// }
editEnterprise(enterpriseId) {
this._showMessage.bind(null, false);
this.setState({ showUpdateForm: true, showFormMessage: false });
return enterpriseId;
}
render() {
console.log("Rendering Enterprises");
if (this.state.showUpdateForm)
let recordId = this.editEnterprise;
if (this.state.isLoading)
return (<div>Loading...</div>);
return (
<div key={this.props.location.pathname}>
<NavigationComponent /><br /><br />
<h3 align="center">Here are all your Enterprises</h3><br />
{this.state.message && <div class="alert alert-success">{this.state.message}</div>}
<Container>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Enterprise</th>
<th>Industry</th>
<th>Business Units</th>
<th>Description</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{
this.state.enterprises.map(
enterprise =>
<tr key={enterprise.id}>
<td>{enterprise.enterpriseName}</td>
<td>{enterprise.industry}</td>
<td>
{enterprise.businessUnits.map(bu =>
<td>{bu.businessUnitName}</td>
)}
</td>
<td>{enterprise.description}</td>
<td><button className="btn btn-warning" onClick={() => this.editEnterprise(enterprise.id)}>Update</button></td>
<td><button className="btn btn-danger" onClick={() => this.removeEnterprise(enterprise.id)}>Delete</button></td>
</tr>
)
}
</tbody>
</Table>
</Container>{" "}{" "}{" "}
<div className="container">
<Button color="primary" size="lg" onClick={this._showMessage.bind(null, true)}>Add Enterprise</Button>{' '}
<Button color="secondary" size="lg" onClick={this._showMessage.bind(null, false)}>Hide</Button>{' '}
{(this.state.showFormMessage && <AddEnterprise showMessage={this._showMessage} {...this.props} />)}
{(this.state.showUpdateForm && <AddEnterprise editEnterprise={this.editEnterprise} showUpdateForm={this.state.showUpdateForm} showMessage={this._showMessage} {...this.props} />)}
</div>
<br /><br />
<FooterComponent />
</div >
);
}
}
export default ListEnterprises;
AddEnterprise (этот же компонент также используется для обновления)
class AddEnterprise extends Component {
emptyEnterprise = {
enterpriseName: "",
industry: "",
description: "",
businessUnits: ""
};
constructor(props) {
super(props);
this.state = {
isLoading: true,
isForm: false,
enterprisePayload: this.emptyEnterprise
}
this.handleChange = this.handleChange.bind(this);
this.addEnterprise = this.addEnterprise.bind(this);
this.editEnterprise = this.editEnterprise.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
let updatedEnterprisePayload = { ...this.state.enterprisePayload };
updatedEnterprisePayload[name] = value;
this.setState({ enterprisePayload: updatedEnterprisePayload });
console.log(updatedEnterprisePayload);
}
editEnterprise() {
this.props.editEnterprise();
}
addEnterprise(event) {
var obj = [];
const businessUnitsData = this.state.enterprisePayload.businessUnits.split(",");
console.log(businessUnitsData);
businessUnitsData.map(x => {
let objVar = new BusinessUnit("", x);
console.log(objVar);
obj.push(objVar);
});
console.log(obj);
let updatedPayload = this.state.enterprisePayload;
updatedPayload["businessUnits"] = obj;
this.setState({ enterprisePayload: updatedPayload });
const payload = this.state.enterprisePayload;
EnterpriseService.addEnterprise(payload)
.then((response) => {
this.setState({ isLoading: false, isForm: true });
this.props.showMessage(false, true); //In React we use state for things like these, you can't always redirect
})
.catch((error) => {
console.log(error);
});
}
render() {
if (this.state.isLoading && this.state.isForm)
return (<div>Loading...</div>);
return (
<div className="base-container">
{!this.props.showUpdateForm && <div className="header"><div><br />Add Enterprise</div></div>}
{this.props.showUpdateForm && <div className="header"><div><br />Update Enterprise</div></div>}
<div className="content">
<div className="form">
<div className="form-group">
<label htmlFor="enterpriseName" for="enterpriseName">Enterprise Name</label>
<input type="text" name="enterpriseName" id="enterpriseName" placeholder="enterpriseName" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="industry" for="industry">Industry</label>
<input type="text" name="industry" id="industry" placeholder="industry" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="businessUnits" for="businessUnits">Business Units</label>
<input type="text" name="businessUnits" id="businessUnits" placeholder="businessUnits" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="description" for="description">Description</label>
<input type="text" name="description" id="description" placeholder="description" onChange={this.handleChange} />
</div>
</div>
</div>
<div className="footer">
{!this.props.showUpdateForm && <button type="button" className="btn" onClick={this.addEnterprise}>Add</button>}
{this.props.showUpdateForm && <button type="button" className="btn" onClick={this.editEnterprise}>Update</button>}
</div>
</div>
);
}
}
export default AddEnterprise;