Redux Store와 REST 유사 API 간의 통신에 필요한 노력을 간소화하세요. 이것은 리소스 상태 관리를 처리하는 axios 및 redux-promise-middleware로 구축된 액션 생성기 함수 및 리듀서 패키지입니다. URL만 있으면 됩니다!
클라이언트는 사용 중인 API를 캡슐화합니다. API에 대한 기본 URL을 제공하여 새 클라이언트를 생성할 수 있습니다.
import { createClient } from 'redux-supermodel'const client = createClient('https://example.com/api/v1')클라이언트 내에서 리소스 정의를 시작할 수 있습니다. 각 리소스는 상호 작용할 수 있는 엔드포인트를 나타냅니다.
// 전체 URL은 https://example.com/api/v1/blogsconst입니다. blogs = client('blogs')// https://example.com/api/v1/commentsconst comments = client('comments' ) 리소스 정의부터 시작하여 http://example.com/api/posts/latest title 및 body 속성이 있는 JSON 개체를 반환한다고 가정해 보겠습니다.
// 'redux-supermodel'의 resources.jsimport { createClient }const client = createClient('http://example.com/api')// GET http://example.com/api/posts/latest/// / { title: '내 최근 블로그 게시물', body: 'Hello, world!' }export const post = client('post', { url: 'posts/latest' }) post.fetch() 고차 구성 요소 connect 사용하여 리소스 상태를 구성 요소에 연결하고 사용하려는 작업 생성자를 바인딩할 수 있습니다. 대부분의 경우 구성 요소가 마운트될 때 무언가를 가져오게 됩니다. 이것이 리소스를 사용하는 유일한 구성 요소인 경우 구성 요소를 마운트 해제할 때 재설정할 수 있습니다. 일반적으로 create 및 update 작업 생성자는 양식의 버튼 또는 제출 핸들러에 바인딩됩니다.
// MyComponent.jsimport React, { Component } from 'react'import { 연결 } from 'react-redux'import { post } from './resources'export class MyComponent extends Component {
async componentDidMount() { try { const res = wait this.props.fetchPost()
// AJAX 액션 생성자는 프라미스이므로 // 작업이 완료된 후 오류를 처리하거나 작업을 수행할 때까지 기다릴 수 있습니다. console.log(res)} catch (error) { // redux-supermodel이 오류 상태를 추적하지만 // 직접 수행할 수도 있습니다. Alert('뭔가 나쁜 일이 일어났습니다!')}
}
// 단일 구성 요소의 컨텍스트 내에서만 리소스에 액세스하고
// 그 자식인 경우, 마운트 해제 시 리소스를 재설정하여 redux 상태를 정리할 수 있습니다.
componentWillUnmount = () => this.props.resetPost()
render() {const { 초기화됨, 오류, 제목, 본문, fetchPost } = this.propsif (!initialized) { if (오류) {return <div className="error">{error.message}</div> } else {return <div className="loading">로드 중...</div>
}}return ( <div><h1>{title}</h1><div className="body"> {body}</div><div className="error"> {error.message}</div>< 버튼 유형="버튼" onClick={fetchPost}>새로고침</button> </div>)
}}내보내기 함수 mapProps(상태) {
const { 준비, 오류, 페이로드 } = 게시(상태)
const { 데이터: { 제목, 본문 } = {} } = 페이로드
return { 준비, 오류, 제목, 본문 }}const actions = {
fetchPost: () => post.fetch({ id: '최신' }),
ResetPost: post.reset,}기본 연결 내보내기(mapProps, actions)(MyComponent) 페이로드는 HTTP 요청 및 응답에 대한 많은 정보를 포함하는 대규모 개체일 수 있으며 그 중 대부분은 구성 요소를 렌더링할 때 필요하지 않으므로 mapProps 호출을 사용하여 페이로드를 단순화하는 것이 좋습니다. 당신이 필요로 할 물건. 페이로드를 직접 사용하지 마십시오. 자세한 내용은 이 블로그 게시물을 확인하세요.
mapProps에 대한 자세한 내용은 React-redux connect() 문서를 읽어보세요.
npm install --save redux-supermodel redux-promise-middleware
redux-promise-middleware 미들웨어와 redux-supermodel 리듀서를 Redux 스토어에 추가해야 합니다.
// store.jsimport { createStore, applyMiddleware, compose, CombineReducers } from 'redux'import promiseMiddleware from 'redux-promise-middleware'import { 리소스로서의 감속기 } from 'redux-supermodel'const rootReducer = CombineReducers({ 리소스 })export 기본 작성(applyMiddleware(promiseMiddleware()))(createStore)(rootReducer)