React+router和react+redux使用過程的記錄
1、集成react+redux的場景。
在不同的路由頁面下,控制公共的頭部顯示和隱藏等功能。因為路由和Header之間不是直接的父組件和子組件的關系,所以通過pros傳參滿足不了。這個時候引入redux共享state(redux的state和component裏的state毫無關系http://www.jianshu.com/p/8287a1dd8ae9)
redux包含三個主要文件action.js主要通過常量定義操作方法;reduer.js主要描述action對應的方法具體操作。Store將state和reduer關聯起來。
2、操作流程
在app.js裏面創建store(store = createStore(todoApp))後
在對應的組件頁面註入state和dispatch到props。這樣在組件裏就可以直接進行調用action裏面對應的方法(原始:使用this.props.dispatch(action);bindActionCreators綁定後用此方法:this.props.showHeader({showHeader:false}))。
function mapStateToProps(state){
return {
header:state.header,
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({showHeader},dispatch)
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(IndexShow);
通過dispatch調用reducer裏面就可以修改state。這樣註入到其他component裏面的state參數也能進行相應的修改。
註意點:
1、Export時如果有header參數則,state的key就是header,否則是showHeaderName
2、監控state的變化時調用此方法監控store寫在單獨文件導出。
let unsubscribe = store.subscribe(() => {
let newState = store.getState() // 獲取更新後最新的
console.log(newState)
// component.setState(...) // 這裏的component可以是this
})
React+router和react+redux使用過程的記錄