Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

0704 #8

Open
LeungKaMing opened this issue Jul 4, 2017 · 0 comments
Open

0704 #8

LeungKaMing opened this issue Jul 4, 2017 · 0 comments

Comments

@LeungKaMing
Copy link
Owner

LeungKaMing commented Jul 4, 2017

工作

对最近几个项目做了总结,避免类似开发时再犯。
#7

话题

在前面零散的Redux基础入门中,我们讨论的action都是同步调用的,每次action触发,state都会马上更新。下面讨论下异步调用action。

  • 异步调用action需要用到redux-thunk来实现
  • 调用同步action creator返回的是一个对象;调用异步action creator返回的是一个函数,参数是dispatch / getState,也可以把当前action creator看成是thunk
  • 异步调用action返回的函数会通过redux-thunk执行,在这个函数内部可以包括网络请求等异步API。
  1. 首先定义一个同步action creator
function add_todo (state) {
  return {
    type: 'ADD_TODO',
    ...state
  }
}

// 另一种带上dispatch的写法:const add_todo = (state) => dispatch( { type: 'ADD_TODO', ...state } )
  1. 然后定义两个同步action creator
// actions.js
function requestPosts (state) {
  return {
    type: 'REQUEST_POSTS',
    ...state
  }
}

function receivePosts (state) {
  return {
    type: 'RECEIVE_POSTS',
    ...state
  }
}
  1. 接着定义中间件redux thunk
// actions.js
function fetchPosts (state) {
  return function (dispath) {
    dispatch(requestPost( { name: 'ljm' } ));  // 在thunk中调用同步action(变成thunk是由于返回的是一个函数)
    dispatch(responsePost( { name: 'ljm' } ));  // 同上
  }
}
  1. 如何使用?
// index.js 入口文件
import thunkMiddleware from 'redux-thunk'  // 导入中间件
import { createStore, applyMiddleware } from 'redux'  // 引入调用中间件函数
import { fetchPosts } from './actions'
import rootReducer from './reducers'

const loggerMiddleware = createLogger()

const store = createStore(
  rootReducer,
  applyMiddleware(
    thunkMiddleware // 初始化store的时候带上,就能允许我们调用异步action creator时用到dispatch了
  )
)

store.dispatch( add_todo({ name: 'ljm' }) ); // dispatch同步action creator返回的对象
store.dispatch(fetchPosts('reactjs')).then(() => console.log(store.getState())); // dispatch异步action creator返回的函数,成功后就会打印当前store的state

redux-thunk 并不是解决异步API调用action的唯一方法。详情见:

@LeungKaMing LeungKaMing mentioned this issue Jul 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant