redux supermodel
v0.19.0
简化您在 Redux Store 和类似 REST 的 API 之间进行通信所需的工作。这是一个使用 axios 和 redux-promise-middleware 构建的动作创建器函数和减速器的包,可以为您处理资源状态管理...您所需要的只是一个 URL!
客户端封装了您正在使用的 API。您可以通过提供 API 的基本 URL 来创建新客户端。
从 'redux-supermodel' 导入 { createClient } 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 对象。
// resources.jsimport { createClient } from 'redux-supermodel' const client = createClient('http://example.com/api')// GET http://example.com/api/posts/latest/// / { title: '我最新的博文', body: '你好,世界!' }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 { async componentDidMount() { try { const res = wait this.props.fetchPost() // AJAX 操作创建者是承诺,因此您可以等待它们 // 处理错误或在错误完成后执行某些操作。 console.log(res)} catch (error) { // redux-supermodel 将为你跟踪错误状态,但是 // 你也可以做你自己的事情。 警报('发生了不好的事情!')} } // 如果您只访问单个组件上下文中的资源并且 // 它的子级,您可以在卸载时重置资源以清理您的 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> }}返回 ( <div><h1>{title}</h1><div className="body"> {body}</div><div className="error"> {error.message}</div><按钮类型=“按钮”onClick={fetchPost}>刷新</按钮> </div>) }}导出函数mapProps(状态){ const { 就绪、错误、负载 } = post(状态) const { 数据: { 标题, 正文 } = {} } = 负载 返回 { 就绪、错误、标题、正文 }}const actions = { fetchPost: () => post.fetch({ id: '最新' }), resetPost: post.reset,}导出默认连接(mapProps, actions)(MyComponent)
有效负载可以是一个巨大的对象,其中包含有关 HTTP 请求和响应的大量信息,其中大部分在渲染组件时都不需要,因此我建议使用mapProps
调用将有效负载简化为你需要的东西。尽量避免直接使用payload。查看这篇博文以进一步阅读。
有关mapProps的详细信息,请阅读react-redux connect()文档。
npm install --save redux-supermodel redux-promise-middleware
您需要将redux-promise-middleware
中间件和redux-supermodel
减速器添加到 Redux Store 中。
// store.jsimport { createStore、applyMiddleware、compose、combineReducers } from 'redux'import PromiseMiddleware from 'redux-promise-middleware'import { reducer 作为资源 } from 'redux-supermodel'const rootReducer =combineReducers({ resource })export默认 compose(applyMiddleware(promiseMiddleware()))(createStore)(rootReducer)