更新的代码!
因此,我尝试获取包含对象数组的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上,我应该如何将状态传递给提交。我试图实现的目的是首先从状态填充表单字段,然后传递更新的状态...但是我完全迷失了。感谢您的任何建议。
答案 0 :(得分:0)
<button onClick={() => this.onSubmit(contacts)}>Save</button>
因此,您将可以在onSubmit
函数中获取当前合同数据。