Loadables - React에서 데이터를 로드하는 간단한 방법
                                            
                                                
                                                
                                                
                                                
                                                
                                                 22917 단어  tutorialwebdevreactjavascript
                    
이 예에서는 할 일 목록을 로드할 것입니다. 여기에서는 상태 관리 솔루션으로 react-redux를 사용하고 있습니다. 아래에서 우리는 react-redux로 스토어와 리듀서를 만드는 방법을 볼 것입니다. 그러나 react-redux-context 저장소에 익숙하다면 "loadables"으로 바로 건너뛸 수 있습니다.
react-redux 컨텍스트 저장소 생성
todos를 저장하기 위한 react-redux-context-store를 생성하는 것부터 시작하겠습니다. 다음 샘플은 react-redux 에서 가져온 것입니다.
// [filename: todo.store.jsx]
import React from 'react'
import {
  Provider,
  createStoreHook,
  createDispatchHook,
  createSelectorHook,
 from "react-redux";
import { createStore } from "redux";
// reducer for the state
import { reducer } from "./store.reducer"
// react context store
const TodoContext = React.createContext(null)
// create redux state selector and dispatch from context
export const useTodoStore = createStoreHook(TodoContext)
export const useTodoDispatch = createDispatchHook(TodoContext)
export const useTodoSelector = createSelectorHook(TodoContext)
// create redux store from the reducer
const todoStore = createStore(reducer)
// create store provider wrap subtree
export function TodoStoreProvider({ children }) {
  return (
    <Provider context={TodoContext} store={todoStore}>
      {children}
    </Provider>
  )
}
스토어 공급자를 생성한 후 리듀서와 스토어에 대한 작업을 정의하는 위치
store.reducer.js를 생성할 것입니다.// [filename: todo.reducer.js]
export const loadNext = () => ({ type: 'load_next' });
export const addTodos = ({ todos, total }) => ({ type: 'add_todos', payload: { todos, total } });
export const setLoading = (loading) => ({ type: 'set_loading', payload: { loading }  });
const InitState = {
 status: 'idle', // idle | pending | resolve | reject 
 todos: [],
 total: 0,
 skip: 0,
 limit: 10
};
export const reducer = (state = InitState, action) => {
  switch (action.type) {
    case 'load_next': {
       if (state.todos.length < state.total && state.status !== 'pending') {
          return {
             ...state,
             status:  'pending'
          };
       }
       return state;
    }
    case 'add_todos': {
      return {
          ...state,
          status: 'resolve',
          todos: [...state.todos, ...action.payload.todos],
          total: state.total + action.payload.todos.length 
      };
    }
    case 'set_loading': {
      return {
          ...state,
          status: action.payload.loading
      };
    }
    default: {
      return state;
    }
  }
};
적재 가능
Loadables는 모든 데이터 로딩 로직을 래핑하고 저장소를 업데이트하는 반응 구성 요소입니다.
// [filename: App.js]
const App = () => (
  <div>
    <TodoStoreProvider>
      {/* Loadable holds all data loading logic*/}
      <TodoLoadable>
        {/* Render todos */}
      </TodoLoadable>
     </TodoStoreProvider>
   </div>
 );
이제 로드 가능 항목을 생성해 보겠습니다.
// [filename: Todo.loadable.js]
function TodoLoadable(props) {
  // react-redux state slice selector
  const skip = useTodoSelector((state) => state.skip);
  const limit = useTodoSelector((state) => state.limit);
  const todoDispatch = useTodoDispatch();
  // load data
  useEffect(() => {
    todoDispatch(setLoading('pending'));
    api({ skip, limit })
      .then((res) => todoDispatch({ todos: res.todos, total: res.total }))
      .catch((e) => todoDispatch(setLoading('reject')));
  }, [skip, limit]);
  // render child
  return <>{props.children}</>
}
여기서 주목해야 할 점은 로딩 로직이 완전히 로딩 가능한 내부에 배치되고 그에 따라 자식이 스토어를 활용하여 UI 상태를 동기화할 수 있다는 것입니다.
IsVisible는 사물을 조건부로 렌더링하는 데 사용할 수 있는 유틸리티 구성 요소입니다.// [filename: IsVisible.utility.jsx]
function IsVisible({ visible, unmountOnExit, ...props }) {   
  if (unmountOnExit && !visible) {
    return null;
  }
  return <div {...props} style={{  ...props.style, display: visible ? 'flex' : 'none'  }} />
}
IsVisible 유틸리티 구성 요소를 사용하여 상태 동기화 UI를 만들 수 있습니다.// [filename: Todo.jsx]
const Error = () => <div><h1>Error</h1></div>;
const Loader = () => <CircularProgress size="small" />
const Todos = () => {
  const todos = useTodoSelector((state) => state.todos);
  return <div>{todos.map((todo) => <h1>{todo}</h1>)}</div>
}
function IsErrorVisible(props) {
  const isError = useTodoSelector((state) => state.status === 'reject');
  return <IsVisible {...props} visible={isError} />
}
....more IsVisible for all API status 'reject' | 'resolve' | 'pending' | 'idle'
이제 이것
IsVisible의 도움으로 API 상태에 따라 UI를 렌더링할 수 있습니다.// [filename: App.js]
const App = () => (
  <div>
    <TodoStoreProvider>
      {/* Loadable holds all data loading logic*/}
      <TodoLoadable>
        <IsErrorVisible><ErrorUI /></IsErrorVisible>
        <IsTodoVisible><Todos /></IsTodoVisible>
        <IsLoaderVisible><Loader /></IsLoaderVisible>
      </TodoLoadable>
     </TodoStoreProvider>
   </div>
 );
이것은
loadable 유틸리티와 함께 IsVisible가 반응에서 데이터를 매우 쉽게 로드하고 코드를 작성하고 이해하기 쉽게 만드는 방법입니다. 다음은 데모 링크입니다Codesandbox..
                Reference
이 문제에 관하여(Loadables - React에서 데이터를 로드하는 간단한 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vtechguys/loadables-a-simple-way-to-load-data-in-react-15ff텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)