最近因为在使用react 构建一个webChatApp 使用了redux ,其中异步请求与websocket请求我都是使用redux-thunk这个facebook官方推荐的中间件来处理大部分的业务。项目源码再此
redux action
通常在react 中发起一个同步请求不使用redux-thunk的时候,action的返回值应该为一个对象,如:
//action.jsconst PULL_SOME_REQ = 'PULL_SOME_REQ';exports pullSomeRequest = (query)=> {return {type: 'PULL_SOME_REQ',payload: query}}
what’s a thunk?
A thunk is a function that wraps an expression to delay its evaluation.
thunk是一个包装表达式以延迟其计算的函数。
那么如何使用呢…
如果需要使用redux-thunk的话,那么必须要通过redux的中间件机制applyMiddleware在redux 创建store的时候注入其中:
import { createStore, applyMiddleware } from 'redux';import thunk from 'redux-thunk';import reducer from './src/store/reducer';const store = createStore(reudcer,applyMiddleware(thunk));
注入store之后自然可以在action中使用thunk func:
//action.jsimport Wilddog from 'wilddog';...let ref = wilddog.ref();export PUlL_SOME_REQ = 'PULL_SOME_REQ';export PULL_SOME_ERR = "PULL_SOME_ERR";export pullSomeRequest = () => {return (dispatch,getState) => {// 如果希望在调用的时候使用promise 请在此处返回一个promisereturn ref.once('value').then((response) => {dispatch({type: 'PULL_SOME_REQ',payload: response}).catch((err)=> {dispatch({type: 'PULL_SOME_ERR',payload: err})})})}}export pushSomeResponse = (msg) => {return (dispatch,getState) => {return ref.child(messages).push(msg).then(response => {dispatch(pullSomeRequest());}).catch(err => {dispatch({type: 'PUSH_SOME_ERR',payload: err})})}}// component/connect.jsimport { connect } from 'react-redux'import { pushSomeResponse } from '../action'@connect(state => state.payload,dispatch => bindActionCreators(pushSomeResponse, dispatch))export Class MessagesList extends React.Component {componentDidMount(){this.props.dispatch(pushSomeResponse('msg')).then(()=> {console.log(this.props)})}}
至此 我理解redux 就如一个server的快照一样一个type 代表一个state 切片式的数据管理方式跟自己之前接触的ember data还是有一定区别,个人学习后有其他感悟再另行补充。