Здесь проблемная строка
// newCtc is empty => so Object.assign, simply returns {test1: 'some value', test2: // somevalue }
// this.setState then merges this into the array, so newCtc is not actually updated
// but the properties test1 and test2
this.setState(Object.assign(this.state.newCtc,{test1:this.state.test1, test2:this.state.test2}));
import React, { Component } from 'react';
import Contact from './Contact';
import TestData from './TestData';
class ContactList extends Component {
constructor(props){
super(props);
this.state = {
name: '',
test1:'',
test2:'',
newCtc:{},
ctcList:[],
arr: []
}
}
async componentDidMount() {
try{
const result = await fetch('https://jsonplaceholder.typicode.com/users')
const data = await result.json()
this.setState({arr:data})
}catch(err){
console.log(err)
}
}
onChangeInput = (e)=>{
const target = e.target;
const name = target.name;
const value = target.value;
console.log(value)
this.setState({
[name]: value
});
}
newSubmit = (e) =>{
e.preventDefault();
const ctcCopy = Object.assign({}, this.state.newCtc);
this.setState({newCtc: Object.assign(ctcCopy, {
test1: this.state.test1,
test2: this.state.test2,
})})
console.log(this.state.newCtc)
this.addContact();
this.clearInput();
console.log(this.state.newCtc);
}
// I would also copy this.state.newCtc
addContact = ()=>{
this.setState({ ctcList:[ ...this.state.ctcList, ...this.state.newCtc] });
console.log(this.state.ctcList);
};
clearInput = ()=>{
this.setState({test1:'',test2:''});
const ctcCopy = Object.assign({}, this.state.newCtc);
this.setState({newCtc: Object.assign(ctcCopy, {
test1: this.state.test1,
test2: this.state.test2,
})})
};
render() {
return (
<div>
<Contact firstName = {this.state.name} lastName='mcdaniel' phoneNumber = '585-721-3824' />
<input type = 'text' name = 'name' onChange = {this.onChangeInput}></input>
<TestData data={this.state.arr} />
<form onSubmit = {this.newSubmit}>
<input type='text' name={'test1'} value={this.state.test1} onChange = {this.onChangeInput}
/>
<input type='text' name={'test2'} value={this.state.test2} onChange = {this.onChangeInput}
/>
<button type='submit'> submit </button>
</form>
</div>
)
}
}
export default ContactList;