參考資料 阮一峰redux教程
Redux 入門教程(一):基本用法 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
Redux 入門教程(二):中間件與異步操作http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
Redux 入門教程(三):React-Redux 的用法http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
使用流程
載入依賴
npm install redux react-redux redux-thunk
<Provide>
組件在根組件外面包裹一層,其中的組件全都可以拿到state
<Provider store={store}>
? ? ?? <div className="App">
? ? ? ?? <PostForm />
? ? ? ?? <Post />
? ? ?? </div>
</Provider>
創(chuàng)建store.js
createStore()的三個參數(shù):reducer,state最初的狀態(tài),applyMiddleware中間件
export const store = createStore(rootReducer,initialState,applyMiddleware(...middleware));
創(chuàng)建reducers文件夾,其中包括rootReducer和部分Reducer
rootReducer為index.js低淡,用來組合所有的Reducer
export default combineReducers({
? posts:postReducer,
})
reducer 的作用:接收當前的state和action,返回新的state
export default function(state=initialState,action){
?? switch(action.type){
? ? ?? default:
? ? ?? return state;
?? }
}
創(chuàng)建actions文件夾和相應(yīng)actions.js
在組件中引入連接connect
connect方法接受兩個參數(shù):mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業(yè)務(wù)邏輯蠕嫁。前者負責輸入邏輯锨天,即將state映射到 UI 組件的參數(shù)(props),后者負責輸出邏輯剃毒,即將用戶對 UI 組件的操作映射成 Action
export default connect(null,{fetchPosts})(Post);
在actions文件夾中新建types.js
里面定義不同的action.type
export const FETCH_POSTS = 'FETCH_POSTS'
postActions.js中引入type
通過dispatch向reducer傳遞action
export function fetchPosts(){
?? return function (dispatch){
? ? ?? fetch("https://jsonplaceholder.typicode.com/posts/")
? ? ?? .then(res=>res.json())
? ? ?? .then(posts=>
? ? ? ? ?? dispatch({
? ? ? ? ? ? ?? type:FETCH_POSTS
? ? ? ? ?? }))
?? }
}
在postReducer.js接收action.type
export default function(state=initialState,action){
?? switch(action.type){
? ? ?? case FETCH_POSTS:
? ? ?? return {
? ? ? ? ?? ...state
? ? ?? }
? ? ?? default:
? ? ?? return state;
?? }
} ?
在post.js中定義mapStateToProps
mapStateToProps是一個函數(shù)病袄。它的作用就是像它的名字那樣,建立一個從(外部的)state對象到(UI 組件的)props對象的映射關(guān)系赘阀。
const mapStateToProps = state =>({
? posts:state.posts.items
})