react sync
1.0.0
使用 HTML5 Fetch 获取 API 数据的声明式方法
react-sync
提供了一个高阶组件,用于从 API 中获取数据
呈现数据是您的责任,但从 API 刷新数据就像更改请求的参数一样简单。让组件管理获取数据的状态。
姓名 | 描述 | 类型 | 必需的 | 默认 |
---|---|---|---|---|
网址 | 不带任何查询参数的 url 获取 | 细绳 | 是的 | |
标头 | 包含要传递给请求的所有标头的对象 | 目的 | 不 | null |
参数 | 包含要传递给请求的所有查询参数的对象 | 目的 | 不 | null |
到查询字符串 | 用于将查询参数 prop 转换为查询字符串的函数 | 功能 | 不 | ./toQueryString.js |
数据 | 接受获取响应对象并返回解析为响应中的数据的承诺的函数 | 功能 | 不 | 默认返回响应 JSON |
孩子们 | 接受对象{promise, data, error} 并返回要渲染的节点的函数 | 功能 | 是的 |
来源:props.jsx
传递给children
属性的函数接收获取状态
姓名 | 描述 | 类型 |
---|---|---|
承诺 | 如果有任何请求未完成,则待处理的承诺 | Promise实例 |
数据 | 从API获取的数据 | toData 结果 |
错误 | 可能发生的任何获取错误 | 错误实例 |
npm install --save react-sync
或者,此项目构建为名为 ReactSync 的 UMD 模块,因此您可以在页面中包含 unpkg 脚本标记
通过脚本标签导入 UMD 模块时查找window.ReactSync
有关过滤的示例用法,请参阅演示源
import React from 'react' ;
import ReactSync from 'react-sync' ;
const StarGazers = ( { owner , repo , githubToken } ) => (
< ReactSync
url = { `https://api.github.com/repos/ ${ owner } / ${ repo } /stargazers` }
headers = { { Authorization : `token ${ githubToken } ` } } >
{
( { promise , data , error } ) => (
< span >
{ promise !== null ? 'Loading...' : data }
</ span >
)
}
</ ReactSync >
) ;
使用此组件时,组合才是王道。
例如,想要每分钟自动重新获取一次?创建一个包装 ReactSync 并每分钟更新一次时间戳查询参数的组件。
import React , { Component } from 'react' ;
import PropTypes from 'prop-types' ;
import Sync from 'react-sync' ;
const now = ( ) => ( new Date ( ) ) . getTime ( ) ;
export default class RefreshSync extends Component {
static propTypes = {
refreshEvery : PropTypes . number
} ;
_timer = null ;
state = {
_ts : now ( )
} ;
triggerNextRefresh = after => {
clearTimeout ( this . _timer ) ;
this . _timer = setTimeout ( this . refresh , after ) ;
} ;
refresh = ( ) => {
this . setState ( { _ts : now ( ) } ) ;
this . triggerNextRefresh ( this . props . refreshEvery ) ;
} ;
componentDidMount ( ) {
this . triggerNextRefresh ( this . props . refreshEvery ) ;
}
componentWillReceiveProps ( { refreshEvery } ) {
if ( refreshEvery !== this . props . refreshEvery ) {
this . triggerNextRefresh ( refreshEvery ) ;
}
}
render ( ) {
const { params , ... rest } = this . props ,
{ _ts } = this . state ;
return < Sync { ... rest } params = { { ... params , _ts } } /> ;
}
}
将上下文中的令牌附加到所有请求怎么样?
import React , { Component } from 'react' ;
import PropTypes from 'prop-types' ;
import Sync from 'react-sync' ;
export default class AuthenticatedSync extends Component {
static contextTypes = {
token : PropTypes . string
} ;
render ( ) {
const { headers , ... rest } = this . props ,
{ token } = this . context ;
return (
< Sync
{ ... rest }
headers = { {
... headers ,
Authorization : token ? `Bearer ${ token } ` : null
} }
/>
) ;
}
}
只默认一个基本 URL 怎么样?
import React from 'react' ;
import Sync from 'react-sync' ;
export const MyApiSync = ( { path , ... rest } ) => (
< Sync { ... rest } url = { [ 'https://my-api.com' , path ] . join ( '/' ) } />
) ;