We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
对最近几个项目做了总结,避免类似开发时再犯。 #7
在前面零散的Redux基础入门中,我们讨论的action都是同步调用的,每次action触发,state都会马上更新。下面讨论下异步调用action。
function add_todo (state) { return { type: 'ADD_TODO', ...state } } // 另一种带上dispatch的写法:const add_todo = (state) => dispatch( { type: 'ADD_TODO', ...state } )
// actions.js function requestPosts (state) { return { type: 'REQUEST_POSTS', ...state } } function receivePosts (state) { return { type: 'RECEIVE_POSTS', ...state } }
// actions.js function fetchPosts (state) { return function (dispath) { dispatch(requestPost( { name: 'ljm' } )); // 在thunk中调用同步action(变成thunk是由于返回的是一个函数) dispatch(responsePost( { name: 'ljm' } )); // 同上 } }
// 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的唯一方法。详情见:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
工作
对最近几个项目做了总结,避免类似开发时再犯。
#7
话题
The text was updated successfully, but these errors were encountered: