redux 使用筆記

參考資料 阮一峰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()的三個(gè)參數(shù):reducer,state最初的狀態(tài),applyMiddleware中間件

export const store = createStore(rootReducer,initialState,applyMiddleware(...middleware));

創(chuàng)建reducers文件夾,其中包括rootReducer和部分Reducer

rootReducer為index.js,用來(lái)組合所有的Reducer

export default combineReducers({

? posts:postReducer,

})

reducer 的作用:接收當(dāng)前的state和action,返回新的state

export default function(state=initialState,action){

?? switch(action.type){

? ? ?? default:

? ? ?? return state;

?? }

}

創(chuàng)建actions文件夾和相應(yīng)actions.js

在組件中引入連接connect

connect方法接受兩個(gè)參數(shù):mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業(yè)務(wù)邏輯。前者負(fù)責(zé)輸入邏輯,即將state映射到 UI 組件的參數(shù)(props),后者負(fù)責(zé)輸出邏輯,即將用戶對(duì) UI 組件的操作映射成 Action

export default connect(null,{fetchPosts})(Post);

在actions文件夾中新建types.js

里面定義不同的action.type

export const FETCH_POSTS = 'FETCH_POSTS'

postActions.js中引入type

通過(guò)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是一個(gè)函數(shù)。它的作用就是像它的名字那樣,建立一個(gè)從(外部的)state對(duì)象到(UI 組件的)props對(duì)象的映射關(guān)系。

const mapStateToProps = state =>({

? posts:state.posts.items

})

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容