技术控

    今日:118| 主题:49179
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Build A Media Library With React, Redux, and Redux-saga – Part 2

[复制链接]
谢谢你忽略 发表于 3 天前
21 3

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
In thefirst part of this tutorial, we had a running app. We covered basic React setup, project workflow; defined basic components and configured our application's routes.
  In part 2 of this tutorial, which is unarguably the most interesting part of building React/Redux application, we will setup application state management with redux, connect our React components to the store, and then deploy to Heroku. We will walk through this part in eight steps:
  
       
  • Define Endpoints of interest.   
  • Create a container component.   
  • Define action creators.   
  • Setup state management system.   
  • Define async task handlers.   
  • Create presentational components.   
  • Connect our React component to Redux store.   
  • Deploy to Heroku.  
  Step 1 of 8: Define Endpoints of interest

  Our interest is the media search endpoints of Flickr API and Shutterstock API.
  Api/api.js

  [code]const FLICKR_API_KEY = 'a46a979f39c49975dbdd23b378e6d3d5';
const SHUTTER_CLIENT_ID = '3434a56d8702085b9226';
const SHUTTER_CLIENT_SECRET = '7698001661a2b347c2017dfd50aebb2519eda578';

// Basic Authentication for accessing Shutterstock API
const basicAuth = () => 'Basic '.concat(window.btoa(`${SHUTTER_CLIENT_ID}:${SHUTTER_CLIENT_SECRET}`));
const authParameters = {
  headers: {
    Authorization: basicAuth()
  }
};

/**
* Description [Access Shutterstock search endpoint for short videos]
* @params { String } searchQuery
* @return { Array }
*/
export const shutterStockVideos = (searchQuery) => {
  const SHUTTERSTOCK_API_ENDPOINT = `https://api.shutterstock.com/v2/videos/search?
  query=${searchQuery}&page=1&per_page=10`;

  return fetch(SHUTTERSTOCK_API_ENDPOINT, authParameters)
  .then(response => {
    return response.json();
  })
  .then(json => {
      return json.data.map(({ id, assets, description }) => ({
        id,
        mediaUrl: assets.preview_mp4.url,
        description
      }));
  });
};

/**
* Description [Access Flickr search endpoint for photos]
* @params { String } searchQuery
* @return { Array }
*/
export const flickrImages = (searchQuery) => {
  const FLICKR_API_ENDPOINT = `https://api.flickr.com/services/rest/?method=flickr.photos.search&text=${searchQuery}&api_key=${FLICKR_API_KEY}&format=json&nojsoncallback=1&per_page=10`;

  return fetch(FLICKR_API_ENDPOINT)
    .then(response => {
      return response.json()
    })
    .then(json => {
      return json.photos.photo.map(({ farm, server, id, secret, title }) => ({
        id,
        title,
        mediaUrl: `https://farm${farm}.staticflickr.com/${server}/${id}_${secret}.jpg`
      }));
    });
};[/code]   First, head to Flickr and Shutterstock to get your credentials or use mine.
   We’re using fetch method from fetch API for our AJAX request. It returns a promise that resolves to the response of such request. We simply format the response of our call using ES6 destructuring assignment before returning to the store.
   We can use jQuery for this task but it’s such a large library with many features, so using it just for AJAX doesn’t make sense.
  Step 2 of 8: Create a container component

  In order to test our application as we walk through the steps, let's define a MediaGalleryPage component which we will update later for a real time sync with our store.
  container/MediaGalleryPage.js

  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;[/code]  We can now add library route and map it to MediaGalleryPage Container.
   Let's update out routes.js for this feature.
  [code]import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './components/HomePage';
import MediaGalleryPage from './containers/MediaGalleryPage';

// Map components to different routes.
// The parent component wraps other components and thus serves as
// the entrance to other React components.
// IndexRoute maps HomePage component to the default route
export default (
  
   
   
  

);[/code]  Let's check it out on the browser console.
   
Build A Media Library With React, Redux, and Redux-saga – Part 2-1 (management,building,interest,running,through)

  We are now certain that we can access our endpoints of interest to fetch images and short videos. We can render the results to the view but we want to separate our React components from our state management system. Some major advantages of this approach are maintainability, readability, predictability, and testability.
  We will be wrapping our heads around some vital concepts in a couple of steps.
  Step 3 of 8: Define action creators

   Action creatorsare functions that return plain Javascript object of action type and an optional payload. So action creators create actions that are dispatched to the store. They are just pure functions.
  Let’s first define our action types in a file and export them for ease of use in other files. They’re constants and it’s a good practice to define them in a separate file(s).
  constants/actionTypes.js

  [code]// It's preferable to keep your action types together.
export const SELECTED_IMAGE = 'SELECTED_IMAGE';
export const FLICKR_IMAGES_SUCCESS = 'FLICKR_IMAGES_SUCCESS';
export const SELECTED_VIDEO = 'SELECTED_VIDEO';
export const SHUTTER_VIDEOS_SUCCESS = 'SHUTTER_VIDEOS_SUCCESS';
export const SEARCH_MEDIA_REQUEST = 'SEARCH_MEDIA_REQUEST';
export const SEARCH_MEDIA_SUCCESS = 'SEARCH_MEDIA_SUCCESS';
export const SEARCH_MEDIA_ERROR = 'SEARCH_MEDIA_ERROR';[/code]  Now, we can use the action types to define our action creators for different actions we need.
  actions/mediaActions.js

  [code]import * as types from '../constants/actionTypes';

// Returns an action type, SELECTED_IMAGE and the image selected
export const selectImageAction = (image) => ({
  type: types.SELECTED_IMAGE,
  image
});

// Returns an action type, SELECTED_VIDEO and the video selected
export const selectVideoAction = (video) => ({
  type: types.SELECTED_VIDEO,
  video
});

// Returns an action type, SEARCH_MEDIA_REQUEST and the search criteria
export const searchMediaAction = (payload) => ({
  type: types.SEARCH_MEDIA_REQUEST,
  payload
});[/code]   The optional arguments in the action creators: payload , image , and video are passed at the site of call/dispatch. Say, a user selects a video clip on our app, selectVideoAction is dispatched which returns SELECTED_VIDEO action type and the selected video as payload. Similarly, when searchMediaAction is dispatched, SEARCH_MEDIA_REQUEST action type and payload are returned.
  Step 4 of 8: Setup state management system

  We have defined the action creators we need and it's time to connect them together. We will setup our reducers and configure our store in this step.
   There are some wonderful concepts here as shown in the diagram inPart 1.
  Let's delve into some definitions and implementations.
   The Store holds the whole state tree of our application but more importantly, it does nothing to it. When an action is dispatched from a React component, it delegates the reducer but passing the current state tree alongside the action object. It only updates its state after the reducer returns a new state.
   Reducers, for short are pure functions that accept the state tree and an action object from the store and returns a new state. No state mutation. No API calls. No side effects. It simply calculates the new state and returns it to the store.
  Let’s wire up our reducers by first setting our initial state. We want to initialize images and videos as an empty array in our own case.
  reducers/initialState.js

  [code]export default {
  images: [],
  videos: []
};[/code]  Our reducers take the current state tree and an action object and then evaluate and return the outcome.
  Let’s check it out.
  reducers/imageReducer.js

  [code]import initialState from './initialState';
import * as types from '../constants/actionTypes';

// Handles image related actions
export default function (state = initialState.images, action) {
  switch (action.type) {
    case types.FLICKR_IMAGES_SUCCESS:
      return [...state, action.images];
    case types.SELECTED_IMAGE:
      return { ...state, selectedImage: action.image };
    default:
      return state;
  }
}[/code]  reducers/videoReducer.js

  [code]import initialState from './initialState';
import * as types from '../constants/actionTypes';

// Handles video related actions
// The idea is to return an updated copy of the state depending on the action type.
export default function (state = initialState.videos, action) {
  switch (action.type) {
    case types.SHUTTER_VIDEOS_SUCCESS:
      return [...state, action.videos];
    case types.SELECTED_VIDEO:
      return { ...state, selectedVideo: action.video };
    default:
      return state;
  }
}[/code]  The two reducers look alike and that’s how simple reducers can be. We use a switch statement to evaluate an action type and then return a new state.
   create-react-appcomes preinstalled with babel-plugin-transform-object-rest-spread that lets you use the spread (…) operator to copy enumerable properties from one object to another in a succinct way.
   For context, { …state, videos: action.videos } evaluates to Object.assign({}, state, action.videos).
  Since reducers don’t mutate state, you would always find yourself using spread operator, to make and update the new copy of the current state tree.
   So, When the reducer receives SELECTED_VIDEO action type, it returns a new copy of the state tree by spreading it( …state ) and updating the selectedVideo property.
  The next step is to register our reducers to a root reducer before passing to the store.
  reducers/index.js

  [code]import { combineReducers } from 'redux';
import images from './imageReducer';
import videos from './videoReducer';

// Combines all reducers to a single reducer function
const rootReducer = combineReducers({
  images,
  videos
});

export default rootReducer;[/code]   We import combineReducers from Redux. CombineReducers is a helper function that combines our images and videos reducers into a single reducer function that we can now pass to the creatorStore function.
   You might be wondering why we’re not passing in key/value pairs to combineReducers function. Yes, you’re right. ES6 allows us to pass in just the property if the key and value are the same.
  Now, we can complete our state management system by creating the store for our app.
  store/configureStore.js

  [code]import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers';
import rootSaga from '../sagas'; // TODO: Next step

//  Returns the store instance
// It can  also take initialState argument when provided
const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  return {
    ...createStore(rootReducer,
      applyMiddleware(sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  };
};

export default configureStore;[/code]  
       
  • Initialize your SagaMiddleWare. We’d discuss about sagas in the next step.   
  • Pass rootReducer and sagaMiddleware to the createStore function to create our redux store.   
  • Finally, we run our sagas. You can either spread them or wire them up to a rootSaga.  
  What are sagas and why use a middleware?
  Step 5 of 8: Define async task handlers

  Handling AJAX is a very important aspect of building web applications and React/Redux application is not an exception. We will look at the libraries to leverage for such task and how they neatly fit into the whole idea of having a state management system.
  You would remember reducers are pure functions and don’t handle side effects or async tasks; this is where redux-saga comes in handy.
   redux-sagais a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better — documentation .
  So, to use redux-saga, we also need to define our own sagas that will handle the necessary async tasks.
  What the heck are sagas?
  Sagas are simply generator functions that abstract the complexities of an asynchronous workflow. It’s a terse way of handling async processes. It’s easy to write, test and reason. Still confused, you might want to revisit the first part of this tutorial if you missed it.
  Let’s first define our watcher saga and work down smoothly.
  sagas/watcher.js

  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;0[/code]  We want a mechanism that ensures any action dispatched to the store which requires making API call is intercepted by the middleware and result of request yielded to the reducer.
   To achieve this, Redux-saga API exposes some methods. We need only four of those for our app: call , put , fork and takeLatest .
  
       
  • takeLatest is a high-level method that merges take and fork effect creators together. It basically takes an action type and runs the function passed to it in a non-blocking manner with the result of the action creator. As the name suggests, takeLatest returns the result of the last call.   
  • watchSearchMedia watches for SEARCH_MEDIA_REQUEST action type and call searchMediaSaga function(saga) with the action’s payload from the action creator.  
   Now, we can define searchMediaSaga ; it serves as a middleman to call our API. Getting interesting right?
  sagas/mediaSaga.js

  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;1[/code]   searchMediaSagais not entirely different from normal functions except the way it handles async tasks.
   callis a redux-saga effect that instructs the middleware to run a specified function with an optional payload.
  Let’s do a quick review of some happenings up there.
  
       
  • searchMediaSaga is called by the watcher saga defined earlier on each time SEARCH_MEDIA_REQUEST is dispatched to store.   
  • It serves as an intermediary between the API and the reducers.  


Build A Media Library With React, Redux, and Redux-saga – Part 2-2 (management,building,interest,running,through)

  
       
  • So, when the saga( searchMediaSaga ) is called, it makes a call to the API with the payload. Then, the result of the promise(resolved or rejected) and an action object is yielded to the reducer using put effect creator. put instructs Redux-saga middleware on what action to dispatch.   
  • Notice, we’re yielding an array of effects. This is because we want them to run concurrently. The default behaviour would be to pause after each yield statement which is not the behaviour we intend.   
  • Finally, if any of the operations fail, we yield a failure action object to the reducer.  
   Let’s wrap up this section by registering our saga to the rootSaga .
  sagas/index.js

  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;2[/code]   forkis an effect creator that provisions the middleware to run a non-blocking call on watchSearchMedia saga.
  Here, we can bundle our watcher sagas as an array and yield them at once if we have more than one.
   Hope by now, you are getting comfortable with the workflow. So far, we’re able to export startForman as our rootSaga .
  How does our React component know what is happening in the state management system?
  Step 6 of 8: Connect our React component to redux store

  I’m super excited that you’re still engaging and we’re about testing our app.
   First, let’s update our index.jsapp’s entry file.
  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;3[/code]  Let’s review what’s going on.
  
       
  • Initialize our store.   
  • Provider component from react-redux makes the store available to the components hierarchy. So, we have to pass the store as props to it. That way, the components below the hierarchy can access the store’s state with connect method call.  
   Now, let's update our MediaGalleryPage component to access the store.
  container/MediaGalleryPage.js

  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;4[/code]   MediaGalleryPagecomponent serves two major purposes:
  a) Sync React Components with the Redux store.
   b) Pass props to our presentational components: PhotoPage and VideoPage . We will create this later in the tutorial to render our content to the page.
  Let’s summarize what's going on.
   React-router exposes two important methods(components) we will use to bind our redux store to our component - connect and Provider.
   connecttakes three optional functions. If any is not defined, it takes the default implementation. It’s a function that returns a function that takes our React component- MediaGalleryPage as an argument.
   mapStateToPropsallows us keep in sync with store's updates and to format our state values before passing as props to the React component. We use ES6 destructuring assignment to extract images and videos from the store’s state.
  Now, everthing is good and we can test our application.
  [code]import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

// We want to get images and videos from the API right after our component renders.
componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));
  }

  render() {
  // TODO: Render videos and images here
  return (
)
  }
}

export default MediaGalleryPage;5[/code]
12下一页
友荐云推荐




上一篇:Answering Featured Snippets Timely, Using Sentence Compression on News
下一篇:PHP ssh2.sftp opendir/readdir fix
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

雨珍 发表于 前天 20:52
我对楼主的敬仰如滔滔江水,绵延不绝!
回复 支持 反对

使用道具 举报

段姿羽 发表于 前天 23:08
LZ是天才,坚定完毕
回复 支持 反对

使用道具 举报

离娟闯 发表于 前天 23:29
不错 支持下
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表