반응형
React는 SPA형태로 동작을 합니다.
따라서 전체페이지를 새로고침 하는 것보다는 필요한 부분만 새로고침 해야 합니다.
기본적으로 부모 컴포넌트에서 자식 컴포넌트로 함수를
props형태로 건네주는 방식으로 동작을 합니다.
즉 고객 추가 컴포넌트에서 부모 컴포넌트의 상태를 변경하는 식으로 필요한 부분만 새로고침 할 수 있도록 설정해야 합니다.
app.js의 state를 삭제해줍니다.
state = {
customers:"",
completed : 0
}
이제 constructor를 작성합니다.
constructor(props) {
super(props);
this.state = {
customers: '',
completed : 0,
}
}
stateRefresh = () => {
this.setState({
customers: '',
completed : 0
});
this.callApi()
.then(res => this.setState({customers : res}))
.catch(err => console.log(err))
}
add에서 고객이 추가되었을 때 stateRefresh가 실행되게 하면 됩니다.
함수 호출을 자식컴포넌에서 하면 부모 컴포넌트의 state값을 경신하게 됩니다.
따라서 render 하는 부분에서
<CustomerAdd stateRefresh={this.stateRefresh}/>
props형태로 보내 주면 됩니다.
다음은 자식 컴포넌트에서 함수를 호출합니다.
handleFormSubmit = (e) =>{
e.preventDefault();
this.addCustomer()
.then( res => console.log)
this.setState ({
file : null,
userName : '',
birthday : '',
gender : '',
job : '',
fileName : ''
})
this.props.stateReFresh();
}
고객 목록 데이터를 불러오는 과정은 비동기적으로 수행되므로 추가 - > 갱신을 순서적으로 보장하지 못합니다.
따라서 순서를 지정해주어야 합니다.
e.preventDefault();
this.addCustomer()
.then((res) => {
console.log(res.data);
this.props.stateReFresh();
})
실제 서비스에서는 전체 목록을 조회하는 것보다는 스크롤을 통해 10개씩 가져오도록 하는 것이 좋습니다.
반응형
'FrontEnd > React' 카테고리의 다른 글
| AppBar 와 웹 폰트 적용 (0) | 2020.07.16 |
|---|---|
| 삭제기능 추가 (0) | 2020.07.13 |
| Express Server에서 처리하기 (0) | 2020.07.13 |
| 이벤트 처리 (0) | 2020.07.13 |
| MySQL DB 구축 (0) | 2020.07.13 |
댓글