项目作者: dat2

项目描述 :
redux-saga + react, experimental
高级语言: JavaScript
项目地址: git://github.com/dat2/react-suspense-saga.git
创建时间: 2018-03-18T16:36:51Z
项目社区:https://github.com/dat2/react-suspense-saga

开源协议:MIT License

下载


Overview

A React component that renders the results of an ES2015 generator.

The suspense is killing me, so I decided to explore this before React implements
it themselves!

Getting started

Install

  1. npm i react-suspense-saga

or

  1. yarn add react-suspense-saga

Quick Example

  1. import runner from 'react-suspense-saga'
  2. import { call, render } from 'react-suspense-saga/lib/effects'
  3. import Api from './Api'
  4. function* greeter() {
  5. yield render(
  6. <p>Loading...</p>
  7. )
  8. try {
  9. const user = yield call(Api.fetchUser)
  10. yield render(
  11. <p>
  12. Hello {user.name}!
  13. </p>
  14. )
  15. } catch(e) {
  16. yield render(
  17. <p>
  18. Oh no, something failed!
  19. </p>
  20. )
  21. }
  22. }
  23. export default runner(greeter)

Examples

API Documentation

Call

  1. call(
  2. func: (...args: Array<any>) => Promise<any>,
  3. ...args: Array<any>
  4. ): Effect

This will instruct the runner to return the results of the promise back to the
generator when it resolves or rejects.

eg.

  1. const AsyncGreeting = runner(function*() {
  2. yield render(<p>Loading...</p>)
  3. try {
  4. const response = yield call(fetch, '/api/user')
  5. const user = yield call(() => response.json())
  6. yield render(<p>Hello { user.name }!</p>)
  7. } catch(e) {
  8. yield render(<p>Something went wrong 🤔</p>)
  9. }
  10. })

delay

  1. delay(
  2. ms: number
  3. ): Effect

This will instruct the runner to use setTimeout.

eg.

  1. const MyComponent = runner(function*() {
  2. yield delay(1000)
  3. yield render(<p>my component</p>)
  4. })

render

  1. render(
  2. node: React.Node | React.Component,
  3. extraProps: Object?
  4. ): Effect

This will render a node or a react component.

eg.

  1. const Loading = () => <p>Loading...</p>
  2. const MyComponent = runner(function*() {
  3. yield render(Loading) // props for MyComponent will get forwarded to this
  4. yield render(<p>my component</p>)
  5. yield render(MyOtherComponent, { name: 'nick' })
  6. })

takeProps

  1. takeProps(): Effect

This will hook into the componentWillReceiveProps lifecycle method, and block your
saga until the props have changed. It will also receive the initial props on
componentDidMount.

eg.

  1. const GreetingWithProps = runner(function*() {
  2. // Every time the props change, we will re-render
  3. while (true) {
  4. const { loading, name } = yield takeProps()
  5. if (loading) {
  6. yield render(<p>Loading...</p>)
  7. } else {
  8. yield render(<p>Hello {name}</p>)
  9. }
  10. }
  11. })