[英]React-redux cross access state value
在過去的兩周中,我一直在與redux一起工作,並且遇到了一個我想訪問/更改另一個reducer的狀態值的問題。 我該如何實現?
例如:我有兩個組件“ A-Component ”和“ Message-component ”,它們分別具有“ A-actions ”,“ Message-actions ”和“ A-reducer ”,“ Message-reducer ”
調用“ A-Component ”操作時,它將調用相應的reducer函數,在該函數中我需要更新Message-reducer狀態值,該狀態值將顯示消息框
export function add(data) { return { types: [types.ONADD, types.ONADDSUCCESS, types.ONADDFAIL], payload: { response: api.add(data).then(response => response), data } }; }
export default createReducer(initialState, { [types.ONADD](state) { return { ...state, message: 'Updating Records' }; } });
上述消息狀態值是消息縮減程序的狀態值。 我想從A-reducer更新消息狀態值,然后再更新消息組件。 在redux中可能嗎?
我嘗試了各種中間件,但是失敗了。
預先感謝!
我認為您正在以錯誤的方式進行處理。 您應該盡可能地標准化數據,然后使用連接裝飾器來組成UI所需的狀態。 例如,消息可以嵌套在“朋友”的節點下,但是最好將它們放在自己的商店中,然后創建一個函數,根據關系從朋友中選擇消息。 這使您可以免費進行匯總(您有3條未讀郵件)。 看一下重新選擇 ,以一種很好的方式(和緩存的方式)執行此操作。
編輯:
您可以編寫可調度多個操作的中間件:
export default (store) => (next) => (action) => {
if(!action.types){
return next(action);
}
action.types.forEach(type => {
next({
type,
payload: action.payload
})
});
}
然后從Action Creator調用它,如下所示:
export function addMessage(message){
return {
types: ['ADD_MESSAGE', 'UPDATE_USER'],
payload: message
}
}
如果您已經在“消息操作”中進行了更新操作
我認為您可以在觸發ONADDSUCCESS時直接調度更新操作。
// Message action
export function MessageUpdate (data) {
return {
type: ...,
data,
}
}
// A action
export function add(data) {
return dispatch => {
dispatch({
type: types.ONADD
});
// code for your add event
api.add(data).then( response => {
(() => {
dispatch(MessageUpdate(response));
return dispatch({
type: types.ONADDSUCCESS,
})
})()
});
}
}
希望這個答案能回答您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.