我會推薦在這裏使用asyncConnect這裏。你得到狀態作爲參數,你可以檢查數據是否存在,如果不存在,你應該加載它!這裏有一個簡單的例子:
@asyncConnect([{
promise: ({ store: { dispatch, getState }, params }) => {
const currentState = getState();
const promises = [];
if (!checkIfNoteExists(currentState)) {
promises.push(dispatch(loadNote(params.id)));
}
if (!checkIfCommentsLoaded(currentState)) {
promises.push(dispatch(loadComments()));
}
if (!checkIfAuthorLoaded(currentState)) {
promises.push(dispatch(loadAuthor()));
}
return Promise.all(promises);
}
}])
@connect(...)
class YouClass extends Component {
...
}
裏面checkIfNoteExists
您需要檢查數據是否存在於當前的狀態,例如,你可以做這樣的事情:
function checkIfNoteExists(state) {
return state.note && state.note.content;
}
這將確保您的數據在那裏,如果不存在,則需要將其添加到承諾數組中。
還有一點很重要,請注意@asyncConnect
適用於服務器和客戶端!同構應用程序FTW!
祝你好運!
爲什麼中間件不是redux-saga或redux-thunk來檢查是否存在註釋並且如果不存在則調用加載操作? – elmeister
@elmeister確實使用了redux-thunk實現了一系列的調度(loadDependant())。但看起來有點打電話交叉組件調用。我有單獨的組件與其reducer,行動 noteslist,notedetail分別居住在不同的文件夾 另一點是使其通用,所以我可以派遣在我的actioncreator {類型:ENSURE_DEPENDANT_EXISTS},這是否有道理? – shnoby
在我看來,最簡單的方法是檢查note是否加載在notes /:id'componentWillMount'中,顯示加載微調或者其他任何不適合的內容,並且當note可用時檢查'componentWillReceiveProps' - 刪除微調和顯示細節。 – elmeister