Redux 및 Redux-Saga와 소통하세요 🪄

독자님 안녕하십니까🙏

이 블로그는 React에서 redux store와 통신하는 과정을 알아볼 것입니다.

Every developer maintain code in a different approach



내 접근 방식: 이 트리 폴더의 폴더 구조 📂는 모델, 서비스, 페이지와 같이 일반적입니다.

1. 모델

const customerModel = {
  namespace: 'customer',
};

export default customerModel;



네임스페이스를 제공하는 것은 스토어 전체에서 고유하며 기억하기 쉽고 효과 및 리듀서를 호출하기 쉽습니다.

고객 모델의 상태를 생성해 보겠습니다.

const customerModel = {
  namespace: 'customer',
  state:{
    customerList: [],
    singleCustomer: {},
  }
};



위의 state 에서 개체는 변경 사항이 발생하는 경우 고객 구성 요소의 업데이트도 Rest API의 응답을 처리합니다.

Rest API와 연결하고 customerList 배열에 응답을 푸시하는 방법을 이해합시다. 이것은 effects 함수를 포함할 generator 객체를 생성하기 때문입니다. 자세히 알아보기generator

redux-saga 일부 특정 작업이 Store로 전달될 때 작업을 생성하기 위해 내부 함수를 래핑하는 도우미 효과를 제공합니다.
effects -

  effects: {
    // * indicate its generator fun
    *setState({ payload }, { put }) {
      if (payload) {
        yield put({
          type: 'save',
          payload,
        });
      }
    },


setState는 사용자 작업, 상태 값 업데이트 등과 같은 여러 항목을 호출하는 데 매우 일반적인 재미입니다. 두 개의 매개변수가 있습니다.
  • { payload } - 상태에서 업데이트하려는 값.
  • { put } - redux-saga의 특별한 도우미 기능입니다. 두 개의 매개변수가 필요합니다. 1. type 감속기 이름( save ), 2. 매장 내 업데이트가 필요한 페이로드, 구성 요소 섹션에서 이해할 페이로드. 자세히 알아보기helper
  • yield - 감속기 put 에 연결 중인 save 의 호출을 반환합니다. save 함수는 아래 코드에서 reducer 객체 섹션에서 선언할 것입니다.



  • reducers -

     reducers: {
        save(state, { payload }) {
          return {
            ...state,
            ...payload
          };
        },
      },
    
    


    리듀서 기능에서 애플리케이션의 상태를 유지하는 논리를 넣을 수 있지만 현재는 이전 상태를 가져오고 변경 사항이 있는 경우 새 상태와 병합하는 중입니다.

    하지만 상단에 있는 고객 목록의 응답을 customerList 배열에 입력하려고 했습니다.

    예: - setState fun에서와 같이 생성기 함수를 만들고 논리를 정의해 보겠습니다.

    *getCustomers({ payload }, { call, put }) {
          try {
            // api call -
            const response = yield call(customerListAPI, payload); 
            if (response.success) {
             // customerList key specified to store only in that array value. 
              yield put({
                type: 'save',
                payload: {
                   customerList: response.data,
                }, 
              });
            }
          } catch (error) {
            console.error('error in customer list api', error);
          }
    },
    
    


    설명 - call 효과의 도움으로 promise 함수를 호출하기 때문에 API 호출을 래핑했습니다.
  • call - 두 개의 매개변수 필요 - i) 콜백 기능, ii) 페이로드 - 콜백 기능에 필요한 데이터를 전달해야 하는 경우 고객 ID 등과 같은 간단한 단어 API 요구 사항에서
  • yield API 호출에서 응답을 받는 순서를 제어합니다.
  • try-catch는 catch가 콘솔에서 프롬프트를 표시할 약속을 해결할 때 오류가 발생하는 기능을 제어하는 ​​데 도움이 됩니다.

  • 2. 서비스

    서비스 폴더에는 관련 API 기능 및 공통 필수 키 값이 포함됩니다.

    
    import { Access, Secret, ApiURL } from '@/utils/env';
    import request from 'umi-request'; 
    // axios also can be used here if you are comfirtable with `umi-request`
    
    const headers = {
      'Content-Type': 'application/json',
      'access': Access,
      'secret': Secret,
    };
    
    export async function customerListAPI(params) {
      return request(`${ApiURL}/v1/getcustomerlist`, {
        headers,
        method: 'GET',
      });
    }
    
    // other async functions ....
    export async function customerByID(params) {
     ....
     ....
     ...
    }
    
    
    


    3. 페이지 또는 구성 요소

    이제 마지막으로 API에서 데이터를 가져오기 위해 모델을 호출해야 합니다.
    UMI 란 무엇이며 연결 방법을 이해하십시오. my article를 확인하십시오.

    
    import { connect } from 'umi';
    
    const CustomerList = (props) => {
      const { dispatch, customer } = props;
      const { customerList } = customer;
      useEffect(() => {
        if (dispatch) {
          dispatch({
            type: 'customer/getCustomers',
            payload: {
              size: 10,
              page: 1,
            },
          });
        }
      }, []);
    
      return (
        <CommonTable
          source={ customerList }
        >
        ....
        </CommonTable>
      );
    };
    // to connec with redux store
    export default connect(({ customer }) => ({
      customer,
    }))(CustomerList);
    
    
    


    Congratulation you made it. 🏆



    즐기고, 배우고, 기억하길 바랍니다...🙌

    If you liked it please leave some 💙 & 👍 to show your support. Also, leave your responses below and reach out to me if you face any issues.



    Twitter에서 저를 찾고 제 개발자 여정을 팔로우할 수 있습니다 ✌️

    감사합니다.

    좋은 웹페이지 즐겨찾기