обновленный код!
Поэтому я пытаюсь получить файл json с массивом объектов, загрузить его в форму редактирования и, нажав кнопку «Отправить», сохранить и обновить массив.
Вот часть моего кода:
import React, {Component} from 'react';
const API = "https://www.mocky.io/v2/581335f71000004204abaf83";
class EditContact extends Component {
constructor(props) {
super(props);
this.state = {
contacts: [],
}
this.handleInputChange = this.handleInputChange.bind(this);
}
componentDidMount() {
fetch(API)
.then(response => response.json())
.then(data => this.setState({ contacts: data.contacts }))
.catch(error => console.log(error));
}
onSubmit(event) {
event.preventDefault();
this.editContact(this.state);
//am I thinking right?
}
editContact(EditWithThisValue)
{
const { contacts } = this.state;
const updated = {
...contacts,
//what goes here
}
}
handleInputChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
console.log(this.state);
}
render() {
const { search, sortIt, sortBy, direction, deleteContact, editContact} = this.props;
const {name, contacts} = this.state;
const contactDetail = (contacts) =>
<ul className="gradient_text" key={contacts.name}>
<li>Name: <input name="name" id="name" onChange={this.handleInputChange} defaultValue={contacts.name}/></li>
<li>Phone: <input name="phone_number" id="phone_number" onChange={this.handleInputChange} defaultValue={contacts.phone_number}/></li>
<li>Address: <input name="address" id="address" onChange={this.handleInputChange} defaultValue={contacts.address}/></li>
<button onClick={() => this.onSubmit(contacts)}>Save</button>
<hr />
</ul>
if (direction === 'notsorted') {
let filteredAndSortedData = contacts.filter(
contacts => {
return contacts.name.toLowerCase().includes(search.toLowerCase()) ||
contacts.address.toLowerCase().includes(search.toLowerCase()) ||
contacts.phone_number.includes(search);
})
return (
<div>
{filteredAndSortedData.map(contactDetail)}
</div>
);
}
else if........
}
}
export default EditContact;
Я застрял на handleInputChange, как я должен передать состояние для отправки. Чего я пытался добиться, чтобы сначала заполнить поля формы из состояния, а затем передать обновленное состояние ... но я полностью потерян. Спасибо за любой совет.