React-redux 交叉访问状态值
React-redux cross access state value
过去两周我一直在使用 redux,我遇到了一个问题,我想 access/change 另一个减速器的状态值。我怎样才能做到这一点?
例如:我有两个组件'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 } }; }
A-减速器
export default createReducer(initialState, { [types.ONADD](state) { return { ...state, message: 'Updating Records' }; } });
上述消息状态值是消息reducer的状态值。我想更新来自 A-reducer 的消息状态值 进而更新消息组件。这在 redux 中可行吗?
我尝试了各种中间件但都失败了。
提前致谢!
我认为您的处理方式有误。你应该尽可能地规范化你的数据,然后也许使用 connect 装饰器来组成你的 UI 所需的状态。例如,Messages 可以嵌套在 "Friend" 的节点下,但最好将它们放在自己的存储中,然后制作一个根据关系选择来自朋友的消息的功能。这为您免费提供聚合(您有 3 条未读消息)。查看 reselect 以找到一种以一种很好的(和缓存的)方式执行此操作的方法。
编辑:
您可以编写调度多个操作的中间件:
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
}
}
如果您在 Message-actions 中已有更新操作
我认为您可以在触发 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,
})
})()
});
}
}
希望这能回答您的问题。