Redux 是 JavaScript 状态(state)管理工具。即Redux不单单适用于React.js,还适用于Angular.js、Backbone.js等框架和库。本文只介绍Redux在React.js中的使用。本文只是我的学习Redux的总结,只是我的理解,不必定百分百准确!读者能够对照 Redux中文文档 或者查看Redux的源码。react
使用redux从建立store开始,经过createStore(rootReducer, [iniState])
建立全局惟一的store,用于统一管理state tree。store建立好之后,view组件经过store.getState()
能够获取state tree。若是须要修改state tree ,必须调用store.dispatch(action)
触发action(action中能够携带操做数据),action触发后,对应的reducer会处理action并返回更新后的state tree。这就是redux的工做原理!ajax
初学者常常搞不清楚redux和react-redux,例如:Provider
是属于redux仍是react-redux的组件?connect()
呢?刚开始我也搞不清楚,直到看了redux的源码之后,总算记住了。redux只对外暴露了如下几个方法,用排除法,其余的都不是redux的方法!其实,react-redux是redux对react的官方绑定库(Official React bindings for Redux),借助react-redux能够很方便的在react中使用redux。json
// redux/lib/src/index.js
export {
createStore,
combineReducers,
bindActionCreators,
applyMiddleware,
compose,
__DO_NOT_USE__ActionTypes
}
复制代码
下面是react-redux的原理,仅供参考!redux
react-redux提供一个叫Provider
的组件,用于将store注入须要使用store的组件promise
// 省略其余代码...
ReactDOM.render(
<Provider store={store}> <App /> </Provider>,
document.getElementById('root')
);
复制代码
提供connect()
方法为须要使用store的组件,绑定state tree
和dispatch()
方法。app
// 省略其余代码...
const mapStateToProps = (state, ownProps) => ({
active: ownProps.filter === state.visibilityFilter
})
const mapDispatchToProps = (dispatch, ownProps) => ({
onClick: () => dispatch(setVisibilityFilter(ownProps.filter))
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Link)
复制代码
react-redux的使用分为三步:框架
经过createStore()方法建立store;异步
经过Provider组件将store注入到须要使用store的组件中;ide
经过connect()链接UI组件和容器组件,从而更新state和dispatch(action)。函数
引入中间件,是由于redux自己不支持异步的action,因此你不能dispatch异步的action(例如:dispatch一个包含ajax请求结果的action)。redux提供一个高阶函数ApplyMiddleware()
,该函数能够将action一级级传递给每个中间件,因为遵循必定的规范,每一个中间件能够处理action并返回新的action,最后一个中间件处理完action才会传递给reducer作出响应。中间件有点像拦截器,看下图就明白了(图片来源)。
看过redux源码的都知道,redux的源码短小精悍,有许多精妙之处。compose()
和applyMiddleware()就是个很好的例子,必须拿出来溜溜~~
compose()
源码// 执行compose(f, g, h) 至关于 (...args) => f(g(h(...args)))
// 将args按顺序注入到每一个函数中,达到一级级传递参数的目的
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
复制代码
applyMiddleware()
源码// 将每一个中间件,按顺序compose到一块儿
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
'Dispatching while constructing your middleware is not allowed. ' +
'Other middleware would not be applied to this dispatch.'
)
}
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
// 让每一个中间件函数携带 middlewareAPI 执行一遍,让每一个中间件均可以getState和dispatch
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
复制代码
以redux-thunk和redux-logger中间件为例,使用createStore()建立中间件时,传入applyMiddleware(),具体看代码。
// src/store.js/js
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk' // 中间件
import { createLogger } from 'redux-logger' // 中间件
import rootReducer from '../reducers'
const loggerMiddleware = createLogger()
export default function configureStore(preloadedState) {
return createStore(
rootReducer,
preloadedState,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
)
)
}
复制代码
// src/index.js
import configureStore from './store/index'
const store = configureStore()
ReactDOM.render(
<Provider store={store}> <App /> </Provider>,
document.getElementById('root')
);
复制代码
使用中间件之后,就能够建立异步的action了
// src/action/index.js
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function requestPosts(data) {
return {
type: REQUEST_POSTS,
data
}
}
function receivePosts(json) {
return {
type: RECEIVE_POSTS,
posts: json.result || []
}
}
function fetchPosts(data) {
return dispatch => {
dispatch(requestPosts(data))
return fetch(`/Joke/NewstImg?key=6b1d549be2a445229921b884c26fad81&page=2&rows=10`)
.then(res => res.json())
.then(json => dispatch(receivePosts(json)))
}
}
export const getJokeList = data => {
return (dispatch, getState) => {
return dispatch(fetchPosts(data))
}
}
复制代码
在reducer中,处理对应的action
// src/reducer/jokes.js
import {
REQUEST_POSTS,
RECEIVE_POSTS
} from '../actions'
const jokes = (state = { posts: [] }, action) => {
switch (action.type) {
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true
})
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
posts: action.posts
})
default:
return state
}
}
export default jokes
复制代码
在UI组件中触发action
// src/components/JokeList.js
import React, { Component } from 'react'
import { getJokeList } from '../actions'
import { connect } from 'react-redux'
class Jokes extends Component {
componentDidMount() {
const { dispatch } = this.props
dispatch(getJokeList()) // 在这里dispatch一个action,通过中间件处理后,最终传给reducer,从而更改state,而后刷新UI
}
render() {
const { posts = [] } = this.props
console.log('render', posts)
return (
<div> <h3>幽默笑话</h3> { posts.map(item => { return <div> <p key={item.hashId}>{item.content}</p> {item.url ? <p><img src={item.url} alt="" /></p> : ''} </div> }) } </div> ) } } function mapStateToProps(state) { const { jokes: { posts = [] } } = state console.log('mapStateToProps-posts', posts) return { posts } } export default connect(mapStateToProps)(Jokes) 复制代码
这就是中间件的用法!
本文完