• React手稿之 React-Saga


    Redux-Saga

    redux-saga 是一个用于管理应用程序副作用(例如异步获取数据,访问浏览器缓存等)的javascript库,它的目标是让副作用管理更容易,执行更高效,测试更简单,处理故障更容易。

    redux-saga相当于一个放置在actionreducer中的垫片。

    之所以称之谓副作用呢,就是为了不让触发一个action时,立即执行reducer。也就是在actionreducer之间做一个事情,比如异步获取数据等。

    redux-saga使用了ES6中的Generator功能,避免了像redux-thunk的回调地狱。

    如何使用

    安装

    ```$ npm install --save redux-saga //或者 $ yarn add redux-saga ```

    示例

    假设有一个UI界面,是根据用户ID显示用户详情的。那么我们需要通过接口从数据库根据userId来获取数据。

    简单起见,我们在本地使用一个json文件来模拟数据库数据。

    
    {
      "297ee83e-4d15-4eb7-8106-e1e5e212933c": {
        "username": "Saga"
      }
    }
    

    创建UI Component

    
    import React from 'react';
    import { USER_FETCH_REQUESTED } from '../../../actions/User';
    
    export default class extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = { userId: '297ee83e-4d15-4eb7-8106-e1e5e212933c' }
      }
    
      render() {
        const { userInfo = {}, dispatch } = this.props;
        return (
          <React.Fragment>
            <button onClick={() => {
              dispatch({ type: USER_FETCH_REQUESTED, payload: { userId: this.state.userId } });
            }}>Get User Info</button>  <span>用户名: {userInfo.username}</span>
          </React.Fragment>
        );
      }
    }
    

    创建saga,这里的saga就相当于action.

    
    import { call, put, takeEvery } from 'redux-saga/effects'
    import { fetchUserApi } from '../api/user';
    import { USER_FETCH_REQUESTED, USER_FETCH_SUCCEEDED, USER_FETCH_FAILED } from '../actions/User';
    
    function* fetchUser({ payload }) {
      try {
        const user = yield call(fetchUserApi, payload.userId);
        yield put({ type: USER_FETCH_SUCCEEDED, user });
      } catch (e) {
        yield put({ type: USER_FETCH_FAILED, message: e.message });
      }
    }
    
    const userSaga = function* () {
      yield takeEvery(USER_FETCH_REQUESTED, fetchUser);
    }
    
    export default userSaga;
    

    关于fetchUserApi,我们会在后面的章节中描述。这里仅获取了json文件中与userId相对应的数据。

    把saga放入store中:

    
    import createSagaMiddleware from 'redux-saga';
    import Sagas from '../sagas/index';
    
    const sagaMiddleware = createSagaMiddleware()
    const store = createStore(
      reducer,
      applyMiddleware(sagaMiddleware)
    )
    sagaMiddleware.run(Sagas)
    

    最后再实现相就的reducer即可:

    
    import { USER_FETCH_SUCCEEDED } from '../actions/User';
    
    const initialState = { user: {} };
    
    export default (state = initialState, action) => {
      switch (action.type) {
        case USER_FETCH_SUCCEEDED:
          return { ...state, user: action.user };
        default:
          return state;
      }
    }
    

    在线示例

    推荐阅读React 手稿

  • 相关阅读:
    每日一篇文献:Robotic pick-and-place of novel objects in clutter with multi-affordance grasping and cross-domain image matching
    每日一篇文献:Intuitive Bare-Hand Teleoperation of a Robotic Manipulator Using Virtual Reality and Leap Motion
    每日一篇文献:Virtual Kinesthetic Teaching for Bimanual Telemanipulation
    HEBI Robotic Arm VR Teleoperation
    「iQuotient Case」AR device teleoperated robotic arm
    VR and Digital Twin Based Teleoperation of Robotic Arm
    HEBI Robotic Arm VR Teleoperation
    Human Robot Interaction
    Immersive Teleoperation Project
    机器人演示学习
  • 原文地址:https://www.cnblogs.com/datiangou/p/10158665.html
Copyright © 2020-2023  润新知