Tech/React

[React] 부모 컴포넌트의 상태 변경을 통한 고객 정보 갱신

lonnie(동현) 2021. 3. 18. 11:24

🛹 부모 컴포넌트의 상태 변경을 통한 고객 정보 갱신

0️⃣ 생성자 함수 만들기 (./client/src/App.js)

props에 생성자 처리해주고 그 안에서 state를 갱신할 수 있도록 해주기

constructor(props){
  super(props);
  this.state = {
    customers : '',
    completed : 0
  }
}

1️⃣ state를 초기화해줄 수 있는 함수 만들기 (./client/src/App.js)

1) 'stateRefresh' 함수를 만들고 데이터 초기화 시키기

stateRefresh = () => {
  this.setState({
    customers : '',
    completed : 0
    });
}

2) 고객 데이터 불러오는 부분 넣어주기

stateRefresh = () => {
  this.setState({
    customers : '',
    completed : 0
    });
  this.callApi()
   .then(res => this.setState({customers : res}))
   .catch(err => console.log(err));
}

2️⃣ 고객 데이터가 새롭게 추가되었을 때 stateRefresh 함수가 수행될 수 있도록 해주기 (./client/src/App.js)

CustomerAdd 컴포넌트가 해당 함수를 호출해서 App 컴포넌트의 state 값을 갱신하게 되는 것이다.

<CustomerAdd stateRefresh = {this.stateRefresh}/>

3️⃣ CutomerAdd에 props 추가해주기 (./client/src/compoents/CustomerAdd.js)

고객을 추가한 이후에 고객 목록을 갱신해야 한다.

this.addCustomer()
   .then((response) => {
      console.log(response.data);
      this.props.stateRefresh();
    })

4️⃣ 마무리

React의 SPA 구현을 위해서 부모 컴포넌트의 state 변경을 통해서 자식 컴포넌트의 데이터를 갱신하는 작업을 완료하였다. 다음으로는 고객 정보를 삭제하는 기능을 구현해보겠다.

728x90
반응형