場景
react
和dva
react
dva
中,採用的是基於redux-saga
的異步解決方案,將異步請求所有收集到effects
中進行統一處理。所以:
yield call(fetchDataAsync, payload)
的結果res
後,以此res
爲payload
,繼續put
另外一個異步action
;yield call(fetchDataAsyncAnother, payload)
;dispatch
第一個異步action
時,除了常見的type
、payload
外,咱們還能夠傳入一個callback
,在獲取到請求的結果res
後,使用yield
調用該callback
,並將res
看成參數傳入,在callback
中,發起另外一個異步action
,以下:// page.js
fetchData = () => {
const { dispatch } = this.props
dispatch({
type: 'page/fetchData',
payload: { pageNumber: 1, pageSize: 30 },
cb: (list) => {
// fetchAnotherData
},
})
}
// models/page.js
effects: {
*fetchData({ payload }, { call, put }) {
const res = yiela call(fetchFn, payload)
const arr = Array.isArray(res.content) ? res.content : []
yield put({
type: 'changeStore',
payload: {
arr
}
})
yield cb && cb(arr)
},
}
複製代碼
React
版本的更新,已經不推薦在componentWillReceiveProps
裏發送異步請求了。目前我的的編碼中,若有相似的需求場景,已所有轉移到componentDiaUpdate
中從新發送異步請求id
組成的數組,在另外一個總的對象數組裏查找對應數據。常見於各類下拉框聯動。好比一個"項目"下拉選擇器和一個「項目參與者」下拉選擇器;在沒有選擇項目的時候,加載全部的參與者;而一旦選擇了某個項目,則只顯示對應的參與者。其實引伸一下,就是一個數組求交、並集的問題redux
const projectListId = [1]
const memberList = [
{projectId: 1, name: '小明', id: xxx},
{projectId: 1, name: '小黑', id: xxx},
{projectId: 2, name: '小黃', id: xxx},
{projectId: 3, name: '小紅', id: xxx},
{projectId: 4, name: '小白', id: xxx}
]
const res = memberList.filter(member => projectListId.indexOf(member.projectId) > -1)
console.log(res)
// [{projectId: 1, name: '小明', id: xxx}, {projectId: 1, name: '小黑', id: xxx}]
複製代碼