頁面發布-分發dispatch(action(:object),action已被connect(mapStateToProps, mapDispatchToProps)(App)映射到組件props )
reducer里的純函式執行,拿到action里回傳的物件資料,賦值給redux中的Store,reducer檔案 與action檔案都是回傳store所需物件資料,兩個檔案對這個物件處理再次細分了,
reducer 純粹賦值 action 對資料的來源,或對資料加以標記等
function createStore(reducer) {
var state;
var listeners = []
function getState() {
return state
}
function subscribe(listener) {
listeners.push(listener)
return function unsubscribe() {
var index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
}
function dispatch(action) {
state = reducer(state, action)
listeners.forEach(listener => listener())
// listeners.forEach(listener => listener.apply(this,action)
/*
*普通觀察者應該是在訂閱回呼函式中處理分發時傳的引數,這里很巧妙的用了實體化時外部傳入的reducer純函式,
*這樣 訂閱的回呼函式 就讓reducer來操作了
*而listener訂閱回呼暫時是對組件的更新,subscribe是在connect連接時訂閱的
*/
}
dispatch({})
return { dispatch, subscribe, getState }
}
這里是connect用于理解的代碼
//connect()是一個將Redux相關的道具注入組件的函式,
//您可以注入資料和回呼,通過調度操作更改資料,
function connect(mapStateToProps, mapDispatchToProps) {
//它讓我們注入組件作為最后一步,這樣人們就可以使用它作為裝飾,
//一般來說你不需要擔心,
return function (WrappedComponent) {
//它回傳一個組件
return class extends React.Component {
render() {
return (
//呈現組件
)
}
componentDidMount() {
//在componentDidMount它記得訂閱商店,這樣就不會錯過更新
this.unsubscribe = store.subscribe(this.handleChange.bind(this))
}
componentWillUnmount() {
//稍后取消訂閱
this.unsubscribe()
}
handleChange() {
//每當存盤狀態改變時,它就會重新呈現,
this.forceUpdate()
}
}
}
}
//這不是真正的實作,而是一個心智模型,
//它跳過了從何處獲取“存盤”的問題(答案:將其放在React背景關系中)
//它跳過了任何性能優化(real connect()確保我們不會徒勞地重新渲染),
//connect()的目的是不必考慮
//訂閱應用商店或自己進行性能優化,以及
//相反,您可以指定如何基于Redux存盤狀態獲取道具:
const ConnectedCounter = connect(
//給定Redux狀態,回傳道具
state => ({
value: state.counter,
}),
//給定Redux調度,回傳回呼道具
dispatch => ({
onIncrement() {
dispatch({ type: 'INCREMENT' })
}
})
)(Counter)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/546648.html
標籤:其他
上一篇:前端設計模式——配接器模式
下一篇:web安全|滲透測驗|網路安全
