redux 个人整理
序
本人工作之余的闲暇时间还是很充裕的。在完成经理安排的任务后,基本上都是在自学,主要是阅读各种技术文档、浏览博客、运行别人写的一些前端demo并观赏与赞叹。在ScorpionJay 同学的带领下,我们决定决定做一个react版的音乐播放SPA(Single Page web Application)。
首选,模仿网易云的界面,因为是程序猿最爱的音乐播放器,不解释!然而,分析网易云的数据请求时,貌似全是403。github上有大牛提供了网易云音乐的一些接口,非常好。所以,对于数据接口,我们最后选择了“哈喽,酷狗!”。
阅读了redux的文档后,并参与了一个练手项目r-music的部分开发后,通过自己的理解,整理了这篇文档。
初学,所以一定会有不详或者错误的地方。
参考文档
开发这个项目,我参阅的学习文档如下:
- React 入门实例教程:http://www.ruanyifeng.com/blog/2015/03/react
- React Router 使用教程:http://www.ruanyifeng.com/blog/2016/05/react_router.html
- ECMAScript 6 入门:http://es6.ruanyifeng.com/
- redux中文文档:http://www.redux.org.cn/
- Redux 入门教程(三)——React-Redux 的用法:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
- Flex 布局教程——语法篇:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
流程图解
通过我自己的理解方式,简单地整理了react、redux、react-redux三者之间的关系图,如下:

通过代码,梳理redux、react-redux
注:下面代码只列出搜索功能的关键部分,源码地址:https://github.com/ScorpionJay/r-music
1. Provider
react-redux提供的Provider组件,可以让容器组件取得state。
src/index.js
import configureStore from './stores'
const store = configureStore()
<Provider store={store}>
<Router history={browserHistory} routes={routers} />
</Provider>
上面代码中,Provider使得Router的所有子组件可以取得state。
import configureStore from './stores'为redux的store,如下:
src/store/index.js
import reducers from '../reducers/index';
export default function(initialState) {
let createStoreWithMiddleware
// 判断环境是否logger
if (process.env.NODE_ENV === 'production') {
createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
}else{
//开发环境在console可以看到整个状态树的实时日志
const logger = createLogger();
createStoreWithMiddleware = applyMiddleware(thunk,logger)(createStore);
}
let store = createStoreWithMiddleware(reducers, initialState);
return store;
};
2. react:Component
src/containers/search.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { searchHotAPI,searchResultAPI,clearSearchResultAPI} from '../actions/search'
class Search extends Component {
constructor(props) {
super(props);
}
componentDidMount(){
const { dispatch } = this.props
dispatch(searchHotAPI())
}
searchEvt(keyword,page=1){
const { dispatch } = this.props;
keyword = keyword || this.refs.keyword.value
if(keyword!=''){
dispatch(searchResultAPI(keyword, page));
}else{
dispatch(clearSearchResultAPI());
}
this.refs.keyword.value = keyword;
}
render() {
const { dispatch,controll,search } = this.props;
return (
<div className='root' style={{fontSize:'1.2rem'}}>
//...
</div>
)
}
}
function map(state) {
return {
search: state.search,
controll: state.music.controll
}
}
export default connect(map)(Search)
react-redux的connect方法,用于从 UI 组件生成容器组件。
上面代码中,connect(map)(Search)使得组件Search可以通过props取得map返回的数据。
dispatch(searchHotAPI())和dispatch(clearSearchResultAPI()),获取数据并分发action。
3. redux
src/actions/search.js
import Config from '../config'
import { spin,spinHidden } from './spin'
import api from '../api'
import Storage from '../storage'
//定义常量
export const SEARCH_HOT = 'SEARCH_HOT'
export const SEARCH_RESULT = 'SEARCH_RESULT'
//actionCreator,这里是一个函数,返回action对象
const searchHot = (obj) => {return {type:SEARCH_HOT, obj}}
const searchResult = (obj) => {return {type:SEARCH_RESULT, obj}}
//搜索热门关键字
export function searchHotAPI(){
return async dispatch => {
try{
let hots = await api( Config.searchHotAPI );
dispatch(searchHot(hots.data.info));
} catch(error) {
console.log(error);
}
}
}
//通过关键字搜索
export function searchResultAPI(keyword,page){
return async dispatch => {
try {
let result = await api( Config.searchResultAPI, 'get', {keyword,page} );
//搜索历史存到localStorage
setSearchHistory(keyword);
dispatch(searchResult(result.data.info));
} catch(error) {
console.log(error);
}
}
}
上面代码中,searchHot和searchResult都是Action creator,即分别返回一个action。
action是一个带有type关键字的对象,如{type:SEARCH_HOT, obj}和{type:SEARCH_RESULT, obj}。
searchHotAPI和searchResultAPI分别返回一个获取数据并分发action的异步函数,一般在容器组件里会调用。
src/reducer/search.js
import { combineReducers } from 'redux'
import { SEARCH_HOT,SEARCH_RESULT } from '../actions/search'
function hots(state = [], action){
switch(action.type) {
case SEARCH_HOT:
return action.obj;
default:
return state;
}
}
function result(state = [], action){
switch(action.type) {
case SEARCH_RESULT:
return action.obj;
default:
return state;
}
}
const Reducers = combineReducers({
hots,result,
})
export default Reducers
上面代码中,hots函数收到名为SEARCH_HOT的 Action 以后,就返回一个新的 State,作为热门搜索的结果。
在src/store/index.js中,开发环境下,引入了中间件redux-logger的createLogger,在浏览器console可以观察到每次reducer的结果,如下:

src/reducer/index.js
import { combineReducers } from 'redux'
//...
import search from './search'
const reducers = combineReducers({
//...
search,
})
export default reducers
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State,然后View发生变化。 combineReducers将多个拆分的reducer合并。
redux 个人整理的更多相关文章
- Redux----Regular的Redux实现整理
Regular的Redux实现整理 什么问题? 组件的树形结构决定了数据的流向,导致的数据传递黑洞 怎么解决? 所有组件都通过中介者传递共享数据 方案: 中介者: (function create ...
- 【原】整理的react相关的一些学习地址,包括 react-router、redux、webpack、flux
因为平时经常去网上找react相关的一些地址,找来找去很麻烦,所以自己整理了一下,不过前面部分不是我整理的, 是出自于:http://www.cnblogs.com/aaronjs/p/4333925 ...
- react与redux学习资料的整理
**重点内容**React学习 1.新手入门可以访问react的官方网站,如果英语不是特别好的同学可以访问中文版的,具体链接http://reactjs.cn/react/index.html 首页有 ...
- React初识整理(五)--Redux和Flux(解决状态传递问题)
Flux 1.引入:在React的应⽤中,状态管理是⼀个⾮常重要的⼯作.我们不会直接对DOM节点进⾏操作,⽽是通过将数据设置给state,由state来同步UI,这种⽅式有个潜在的问题,每个组件都有独 ...
- redux学习
redux学习: 1.应用只有一个store,用于保存整个应用的所有的状态数据信息,即state,一个state对应一个页面的所需信息 注意:他只负责保存state,接收action, 从store. ...
- 我要成为前端工程师!给 JavaScript 新手的建议与学习资源整理
来源于:http://blog.miniasp.com/post/2016/02/02/JavaScript-novice-advice-and-learning-resources.aspx 今年有 ...
- Redux原理(一):Store实现分析
写在前面 写React也有段时间了,一直也是用Redux管理数据流,最近正好有时间分析下源码,一方面希望对Redux有一些理论上的认识:另一方面也学习下框架编程的思维方式. Redux如何管理stat ...
- 微信小程序(应用号)资源汇总整理
微信小应用资源汇总整理 开源项目 WeApp - 微信小程序版的微信 wechat-weapp-redux-todos - 微信小程序集成Redux实现的Todo list wechat-weapp- ...
- Redux教程1:环境搭建,初写Redux
如果将React比喻成士兵的话,你的程序还需要一位将军,去管理士兵(的状态),而Redux恰好是一位好将军,简单高效: 相比起React的学习曲线,Redux的稍微平坦一些:本系列教程,将以" ...
随机推荐
- 使用JS实现2048小游戏
JS实现2048小游戏源码 效果图: 代码如下,复制即可使用: (适用浏览器:360.FireFox.Chrome.Opera.傲游.搜狗.世界之窗. 不支持Safari.IE8及以下浏览器.) &l ...
- 漂亮的SVG时钟
漂亮的SVG时钟 效果图: 代码如下,复制即可使用: <!DOCTYPE html> <html lang="en"> <head> <m ...
- css3在动画完成后执行事件
第一种方法: 用计时器,设定一个和动画时长一样的time,过time事件去执行这个函数. setTimeout(function(){ },time); 第二种方法: 当-webkit-animati ...
- (二)Mybatis项目配置
第一节:environments Mybatis支持多个环境,可以任意配置 <environments default="development"> <envir ...
- Emacs 启动优化二三事
Emacs 启动优化二三事 */--> div.org-src-container { font-size: 85%; font-family: monospace; } p {font-siz ...
- Struts DynaActionForm example
The Struts DynaActionForm class is an interesting feature to let you create a form bean dynamically ...
- 拉格朗日(Lagrange)插值算法
拉格朗日插值(Lagrange interpolation)是一种多项式插值方法,指插值条件中不出现被插函数导数值,过n+1个样点,满足如下图的插值条件的多项式.也叫做拉格朗日公式. 这里以拉格朗日 ...
- JDBC连接池和DBUtils
本节内容: JDBC连接池 DBUtils 一.JDBC连接池 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采取连接池技术,来共享连接Conne ...
- ASP.NET MVC5+ 路由特性
概述 ASP.NET MVC 5支持一种新的路由协议,称为路由特性. MVC5也支持以前定义路由的方式,你可以在一个项目中混合使用这两种方式来定义路由. 案例 1.使用Visual Studio 20 ...
- 8-10 Coping Books uva714
题意:把一个包含m个正整数的序列划分为k个 1<=k<=m<=500的非空连续子序列 使得每个正整数恰好属于一个序列 设第i个序列的各个数之和为 Si 你的任务是让所有的 ...