從數(shù)據(jù)到界面響應(yīng)流程
用戶在界面上操作,發(fā)起action,action在reducer中改變store上的數(shù)據(jù),或者在saga中調(diào)接口改變數(shù)據(jù),促使頁面刷新
1.ManagementConsole項(xiàng)目執(zhí)行npm run dev
解決:先執(zhí)行npm run build-libs-dev
- 交互流程:
① Index.tsx -> action ->reducer ->store(app.tsx)
② Index.tsx -> action ->saga -> reducer ->store(app.tsx)
Reducer :(state,action)=>newstate
(以 作業(yè)中心 -> 布置作業(yè) ->個人草稿 初始化界面數(shù)據(jù)的獲取為例 )頁面加載出來觸發(fā)數(shù)據(jù)的獲取
③ 首先在 個人草稿 對應(yīng)的頁面組件中觸發(fā)action的地方
④ 開始找action
⑤ Saga
⑥ 返回到action
⑦ 進(jìn)入reducer(在此返回saga請求所得數(shù)據(jù)給頁面組件)
- 以 作業(yè)中心 -> 布置作業(yè) ->個人草稿 刪除某個記錄為例
① 頁面觸發(fā)action
② action
③ saga
④ action
⑤ reducer
- connect方法接受兩個參數(shù): State和Dispatch。它們定義了 UI 組件的業(yè)務(wù)邏輯。前者負(fù)責(zé)輸入邏輯,即將state映射到 UI 組件的參數(shù)(props),后者負(fù)責(zé)輸出邏輯,即將用戶對 UI 組件的操作映射成 Action。
注意:對于其中的editDate: editDateSelector(state),有兩種寫法(冒號左邊的editDate代表UI組件同名的參數(shù),右邊的editDateSelector是一個函數(shù) 可以從state算出editDate的值):
① editDate: editDateSelector(state),通過selector
② 跳過selector
editDate: state.getEditDataReducer.getEditData,
注意:拿getRequestEidtData鍵值對進(jìn)行說明
冒號左邊的是UI組件對應(yīng)的同名參數(shù),右邊的函數(shù)定義了UI組件的參數(shù)怎樣發(fā)出Action
額外理解
1. 在入口文件app.tsx中引入了react-hot-loader中的AppContainer組件,這個組件下的所有子組件都會在發(fā)生變化時觸發(fā)熱更新
2.<AppContainer />是一個處理reloading的組件,它同樣會處理錯誤。Root組件必須嵌套在AppContainer里面作為子組件,當(dāng)在生產(chǎn)模式的時候,AppContainer會自動禁用,只是簡單的返回子組件
- Store
Store 就是保存數(shù)據(jù)的地方,可以把它看成一個容器,整個應(yīng)用只能有一個 Store。Redux 提供createStore這個函數(shù)來生成 Store。
上面代碼中,createStore函數(shù)接受另一個函數(shù)作為參數(shù),返回新生成的 Store 對象。在生成 Store 的時候,將 Reducer 傳入createStore方法dispatch方法會觸發(fā) Reducer 的自動執(zhí)行
const store = createStore(
createReducer(undefined),
composeEnhancers( applyMiddleware(sagaMiddleware, reduxRouterMiddleware))
);
- State
Store對象包含所有數(shù)據(jù)。如果想得到某個時點(diǎn)的數(shù)據(jù),就要對 Store 生成快照。這種時點(diǎn)的數(shù)據(jù)集合,就叫做 State。當(dāng)前時刻的 State,可以通過store.getState()拿到。
- Action
State 的變化,會導(dǎo)致 View 的變化。但是,用戶接觸不到 State,只能接觸到 View。所以,State 的變化必須是 View 導(dǎo)致的。Action 就是 View 發(fā)出的通知,表示 State 應(yīng)該要發(fā)生變化了。改變 State 的唯一辦法,就是使用 Action。它會運(yùn)送數(shù)據(jù)到 Store。
- Dispatch
dispatch()是 View 發(fā)出 Action 的唯一方法,dispatch接受一個 Action 對象作為參數(shù),將它發(fā)送出去
- Reducer
Store 收到 Action 以后,必須給出一個新的 State,這樣 View 才會發(fā)生變化。這種 State 的計(jì)算過程(邏輯處理)就叫做 Reducer。Reducer 是一個函數(shù),它接受 Action 和當(dāng)前 State 作為參數(shù),返回一個新的 State。
const reducer = function (state, action) {
// ...
return new_state;
};
[DRAFT_INIT_SUCCEEDED]: (state, action: Action<any>) => {
return Object.assign({},state,{
initDraftData: action.payload
});
},
總reducer
combineReducers()做的就是產(chǎn)生一個整體的 Reducer 函數(shù)。該函數(shù)根據(jù) State 的 key 去執(zhí)行相應(yīng)的子 Reducer,并將返回結(jié)果合并成一個大的 State 對象
- redux-thunk 中間件
Action 是由store.dispatch方法發(fā)送的。而store.dispatch方法正常情況下,參數(shù)只能是對象,不能是函數(shù)。這時,就要使用中間件redux-thunk。
import reducer from './reducers';
// Note: this API requires redux@>=3.1.0
const store = createStore(
reducer,
applyMiddleware(thunk)
);
上面代碼使用redux-thunk中間件,改造store.dispatch,使得store.dispatch可以接受函數(shù)作為參數(shù)。
因此,異步操作的第一種解決方案就是,寫出一個返回函數(shù)的 Action Creator,然后使用redux-thunk中間件改造store.dispatch。(在線教育使用的就是該方案)
- redux-promise 中間件
既然 Action Creator 可以返回函數(shù),當(dāng)然也可以返回其他值。另一種異步操作的解決方案,就是讓 Action Creator 返回一個 Promise 對象。
這就需要使用redux-promise中間件。
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import reducer from './reducers';
const store = createStore(
reducer,
applyMiddleware(promiseMiddleware)
);
這個中間件使得store.dispatch方法可以接受 Promise 對象作為參數(shù)。這時,Action Creator 有兩種寫法。寫法一,返回值是一個 Promise 對象。
const fetchPosts =
(dispatch, postTitle) => new Promise(function (resolve, reject) {
dispatch(requestPosts(postTitle));
return fetch(`/some/API/${postTitle}.json`)
.then(response => {
type: 'FETCH_POSTS',
payload: response.json()
});
});
寫法二,Action 對象的payload屬性是一個 Promise 對象。這需要從redux-actions模塊引入createAction方法,并且寫法也要變成下面這樣。
import { createAction } from 'redux-actions';
class AsyncApp extends Component {
componentDidMount() {
const { dispatch, selectedPost } = this.props
// 發(fā)出同步 Action
dispatch(requestPosts(selectedPost));
// 發(fā)出異步 Action
dispatch(createAction(
'FETCH_POSTS',
fetch(`/some/API/${postTitle}.json`)
.then(response => response.json())
));
}
上面代碼中,第二個dispatch方法發(fā)出的是異步 Action,只有等到操作結(jié)束,這個 Action 才會實(shí)際發(fā)出。注意,createAction的第二個參數(shù)必須是一個 Promise 對象。
React-Redux 將所有組件分成兩大類:UI 組件(presentational component)和容器組件(container component)。UI 組件負(fù)責(zé) UI 的呈現(xiàn),容器組件負(fù)責(zé)管理數(shù)據(jù)和邏輯。
如果一個組件既有 UI 又有業(yè)務(wù)邏輯,那怎么辦?回答是,將它拆分成下面的結(jié)構(gòu):外面是一個容器組件,里面包了一個UI 組件。前者負(fù)責(zé)與外部的通信,將數(shù)據(jù)傳給后者,由后者渲染出視圖。
React-Redux 規(guī)定,所有的 UI 組件都由用戶提供,容器組件則是由 React-Redux 自動生成。也就是說,用戶負(fù)責(zé)視覺層,狀態(tài)管理則是全部交給它。
- UI 組件
UI 組件有以下幾個特征
§ 只負(fù)責(zé) UI 的呈現(xiàn),不帶有任何業(yè)務(wù)邏輯
§ 沒有狀態(tài)(即不使用this.state這個變量)
§ 所有數(shù)據(jù)都由參數(shù)(this.props)提供
§ 不使用任何 Redux 的 API
因?yàn)椴缓袪顟B(tài),UI 組件又稱為"純組件",即它純函數(shù)一樣,純粹由參數(shù)決定它的值。
- 容器組件
容器組件的特征恰恰相反。
§ 負(fù)責(zé)管理數(shù)據(jù)和業(yè)務(wù)邏輯,不負(fù)責(zé) UI 的呈現(xiàn)
§ 帶有內(nèi)部狀態(tài)
§ 使用 Redux 的 API
- connect()
React-Redux 提供connect方法,用于從 UI 組件生成容器組件。connect的意思,就是將這兩種組件連起來
import { connect } from 'react-redux'
const VisibleTodoList = connect()(TodoList);
上面代碼中,TodoList是 UI 組件,VisibleTodoList就是由 React-Redux 通過connect方法自動生成的容器組件。
但是,因?yàn)闆]有定義業(yè)務(wù)邏輯,上面這個容器組件毫無意義,只是 UI 組件的一個單純的包裝層。為了定義業(yè)務(wù)邏輯,需要給出下面兩方面的信息:
(1)輸入邏輯:外部的數(shù)據(jù)(即state
對象)如何轉(zhuǎn)換為 UI 組件的參數(shù)
(2)輸出邏輯:用戶發(fā)出的動作如何變?yōu)?Action 對象,從 UI 組件傳出去
因此,connect
方法的完整 API 如下。
import { connect } from 'react-redux'
const VisibleTodoList = connect(
mapStateToProps, //connect第一個參數(shù),是一個函數(shù) 執(zhí)行后返回一個對象
mapDispatchToProps //第二個參數(shù),可以是一個函數(shù)或?qū)ο髨?zhí)行后返回一個對象
)(TodoList)
上面代碼中,connect方法接受兩個參數(shù):mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業(yè)務(wù)邏輯。前者負(fù)責(zé)輸入邏輯,即將state映射到 UI 組件的參數(shù)(props),后者負(fù)責(zé)輸出邏輯,即將用戶對 UI 組件的操作映射成 Action。
- mapStateToProps()
mapStateToProps是一個函數(shù)。它的作用就是像它的名字那樣,建立一個從(外部的)state對象到(UI 組件的)props對象的映射關(guān)系。
作為函數(shù),mapStateToProps執(zhí)行后應(yīng)該返回一個對象,里面的每一個鍵值對就是一個映射。請看下面的例子。
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
上面代碼中,mapStateToProps是一個函數(shù),它接受state作為參數(shù),返回一個對象。這個對象有一個todos屬性,代表 UI 組件的同名參數(shù),后面的getVisibleTodos也是一個函數(shù),可以從state算出 todos 的值。
下面就是getVisibleTodos的一個例子,用來算出todos。
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed)
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed)
default:
throw new Error('Unknown filter: ' + filter)
}
}
mapStateToProps會訂閱 Store,每當(dāng)state更新的時候,就會自動執(zhí)行,重新計(jì)算 UI 組件的參數(shù),從而觸發(fā) UI 組件的重新渲染。
mapStateToProps
的第一個參數(shù)總是state
對象,還可以使用第二個參數(shù),代表容器組件的props
對象
// 容器組件的代碼
// <FilterLink filter="SHOW_ALL">
// All
// </FilterLink>
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}
使用ownProps作為參數(shù)后,如果容器組件的參數(shù)發(fā)生變化,也會引發(fā) UI 組件重新渲染。
connect方法可以省略mapStateToProps參數(shù),那樣的話,UI 組件就不會訂閱Store,就是說 Store 的更新不會引起 UI 組件的更新
- mapDispatchToProps()
mapDispatchToProps是connect函數(shù)的第二個參數(shù),用來建立 UI 組件的參數(shù)到store.dispatch方法的映射。也就是說,它定義了哪些用戶的操作應(yīng)該當(dāng)作 Action,傳給 Store。它可以是一個函數(shù),也可以是一個對象。
如果mapDispatchToProps是一個函數(shù),會得到dispatch和ownProps(容器組件的props對象)兩個參數(shù)。
const mapDispatchToProps = (
dispatch,
ownProps
) => {
return {
onClick: () => {
dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: ownProps.filter
});
}
};
}
從上面代碼可以看到,mapDispatchToProps作為函數(shù)應(yīng)該返回一個對象,該對象的每個鍵值對都是一個映射,定義了UI組件的參數(shù)怎樣發(fā)出Action
如果mapDispatchToProps是一個對象,它的每個鍵名也是對應(yīng) UI 組件的同名參數(shù),鍵值應(yīng)該是一個函數(shù),會被當(dāng)作 Action creator ,返回的 Action 會由 Redux 自動發(fā)出。舉例來說,上面的mapDispatchToProps寫成對象就是下面這樣
const mapDispatchToProps = {
onClick: (filter) => {
type: 'SET_VISIBILITY_FILTER',
filter: filter
};
}
- <Provider> 組件
Connect方法生成容器組件后,需要讓容器組件拿到state對象才能生成UI組件的參數(shù)
一種解決方法是將state對象作為參數(shù)傳入容器組件,但是這樣做比較麻煩,尤其是容器組件可能在很深的層級,一級級將state傳下去將很麻煩
React-Redux提供Provider組件,可以讓容器拿到state (可以結(jié)合TeacherClient項(xiàng)目理解)
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
let store = createStore(todoApp);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
上面代碼中,Provider在根組件外面包了一層,這樣一來,App的所有子組件就默認(rèn)都可以拿到state了
關(guān)于調(diào)用后端接口
接口的調(diào)用都是需要access_token的,財(cái)聯(lián)邦的是在接口url后拼access_token和sessionId,芝士網(wǎng)是傳authorization
有關(guān)Token(authorization—--接口調(diào)用需要的參數(shù))
(以CourseManagement工程為例)
-
在image.png
中,先主動判斷authorization是否有值,有就請求request()正常加載頭部的Tab,沒有值就請求requestToken((window as GlobalDefinitions).user)獲取
- 有了authorization,也就是用戶登錄了,工程中的接口就可以調(diào)用了(以獲取學(xué)生信息為例)