react#3

Gyus·2021년 9월 22일
0

리액트 프로젝트

목록 보기
3/3

Ajax

  • 서버에 새로고침 없이 요청을 할 수 있게 도와준다.

Axios

  • 서버에서 데이터를 받게 해주는 기능
npm install axios
  • npm을 이용해서 설치할 수 있다.
axios.get('https://codingapple1.github.io/shop/data2.json')
                    .then((result) => {
                        console.log(result);
                        })
                    })
                    .catch((err) => {
                        console.log(err)
                    })
  • then은 성공시에 나오는 기능
  • catch는 오류 시에 나오는 기능

Context

  • component가 중첩될 때 유용한 기능.
  • 불편하다고 생각해서 Redux로 대체할생각

Redux

  • props 없이 모든 컴포넌트들이 state를 사용할 수 있게 만들어 준다.
npm install redux react-redux
  • index파일의 App태그에 Provider태그를 감싸준다.
import { Provider } from 'react-redux';

let store = createStore( ()=>{ return [{ id: 0, name : 'coolShoes', quan : '2'}] });

<Provider store={store}>
            <App />
          </Provider>
  • createStore는 object를 리턴해주는 기능이다.
  • Provider태그에 store={store}를 넣어주면 하위 모든 태그에 store를 사용할수 있다.
function stateToProps(state) {
    return {
        state : state
    }
}

export default connect(stateToProps)(Cart)
  • 위 코드 처럼 state를 props형태로 변환시켜주고 connect로 연결 시켜주면 state를 하위태그에 쓸수 있다.

reducer

  • reducer은 state를 업데이트하는 기능
function reducer(state = defaultState, action){
    if ( action.type === 'increase'){

        let copiedState = [...state];
        copiedState[0].quan++;
        return copiedState

    }else if( action.type === 'decrease' ){
        let copiedState = [...state];
        copiedState[0].quan--;
        return copiedState

    } else {
        return state
    }

}

dispatch

  • dispatch는 reducer을 호출하는 기능
function reducer(state = defaultState, action){
    if ( action.type === 'increase'){

        let copiedState = [...state];
        copiedState[0].quan++;
        return copiedState

    }else if( action.type === 'decrease' ){
        let copiedState = [...state];
        copiedState[0].quan--;
        return copiedState

    } else {
        return state
    }


}

Reducer 또 쓰기

let alertState = true;
// state가 많이 필요하면 reducer많이 만들어야한다.
function reducer2(state=alertState, action){
  if(action.type === 'close'){
      state = false;
      return state
  }else{
      return state;
  }

}

let store = createStore(combineReducers({reducer,reducer2}));
  • 이렇게 또 쓸 수가 있다. combineReducers는 모든 reducer들을 묶을수 있다.
  • 이처럼 reducer은 작은 앱에 쓰기에는 너무 복잡하고 시간소모가 많이 되지만, 앱프로젝트시 수백개의 컴포넌트를 관리할 수있는 좋은 리팩터링 방법이다.
profile
푸로구래머

0개의 댓글