Redux ストアと 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 オブジェクトを返すと仮定しましょう。
// resource.jsimport { createClient } from 'redux-supermodel'const client = createClient('http://example.com/api')// GET http://example.com/api/posts/latest/// / { タイトル: '私の最新のブログ投稿'、本文: 'Hello, world!' }export const post = client('post', { url: 'posts/latest' }) post.fetch()
上位コンポーネントのconnect
使用して、リソース状態をコンポーネントにアタッチし、使用するアクション クリエーターをバインドできます。ほとんどの場合、コンポーネントがマウントされるときに何かをフェッチします。これがリソースを使用する唯一のコンポーネントである場合は、コンポーネントがアンマウントされるときにリソースをリセットできます。通常、 create
およびupdate
アクションの作成者は、フォーム上のボタンまたは送信ハンドラーにバインドされます。
// MyComponent.jsimport React, { Component } from 'react'import { connect } from 'react-redux'import { post } from './resources'export class MyComponent extends Component { asyncComponentDidMount() { try { const res = await this.props.fetchPost() // AJAX アクション クリエーターは Promise であるため、 // アクション クリエーターが終了後にエラーを処理したり、何かを実行したりするのを待つことができます。 console.log(res)} catch (error) { // redux-supermodel がエラー状態を追跡しますが、 // 独自の処理を行うこともできます。 alert('何か悪いことが起こりました!')} } // 単一コンポーネントのコンテキスト内でのみリソースにアクセスしたことがあり、 // その子、アンマウント時にリソースをリセットして redux 状態をクリーンアップできます。 ComponentWillUnmount = () => this.props.resetPost() render() {const { 初期化済み、エラー、タイトル、本文、fetchPost } = this.propsif (!initialized) { if (error) {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>< button type="button" onClick={fetchPost}>更新</button> </div>) }}エクスポート関数mapProps (状態) { const { 準備完了、エラー、ペイロード } = post(状態) const { データ: { タイトル、本文 } = {} } = ペイロード return { 準備完了、エラー、タイトル、本文 }}const アクション = { fetchPost: () => post.fetch({ id: 'latest' }), リセットポスト: post.reset,} デフォルトの接続をエクスポート(mapProps, アクション)(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, combinReducers } from 'redux'import PromiseMiddleware from 'redux-promise-middleware'import { resource as resource } from 'redux-supermodel'const rootReducer = combinReducers({ resource })exportデフォルトcompose(applyMiddleware(promiseMiddleware()))(createStore)(rootReducer)