【发布时间】:2021-10-28 17:10:44
【问题描述】:
在 Redux 中,我目前的状态如下所示。
{
activeConversation: "Jim"
conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
user: {id: 8, username: "josh", email: ""}
}
我目前有一个向对话数组添加新消息的函数。这是它的工作原理;它首先在thunk 中调用它。
export const postMessage = (body) => async (dispatch) => {
try {
if (!body.conversationId) {
dispatch(addConversation(body.recipientId, data.message));
} else {
dispatch(setNewMessage(data.message));
}
} catch (error) {
console.error(error);
}
};
如果conversationId 存在,那么它会在Actions 中调用setNewMessage。
const SET_MESSAGE = "SET_MESSAGE";
export const setNewMessage = (message, sender) => {
return {
type: SET_MESSAGE,
payload: { message, sender: sender || null },
};
};
const reducer = (state = [], action) => {
switch (action.type) {
case SET_MESSAGE:
return addMessageToStore(state, action.payload);
default:
return state;
}
};
export default reducer;
问题在于此操作中的状态仅包含对话数组,而不包含其他任何内容。我需要的是还拥有activeConversation,这样我就可以在我的减速器功能中使用它。我不太清楚状态是如何工作的,所以我不知道为什么只有对话数组出现在 state 中而不是其他任何东西。
另外,activeConversation 的设置方式如下。
const SET_ACTIVE_CHAT = "SET_ACTIVE_CHAT";
export const setActiveChat = (username) => {
return {
type: SET_ACTIVE_CHAT,
username
};
};
const reducer = (state = "", action) => {
switch (action.type) {
case SET_ACTIVE_CHAT: {
return action.username;
}
default:
return state;
}
};
我想知道如何为我的 set message reducer 函数获取 activeConversation 状态。
【问题讨论】:
-
动作没有状态,但我想我明白了。听起来您想在同一个 reducer 函数中同时引用
activeConversation和conversations数组。为此,应该将 state 和 reducer 函数结合起来,换句话说,您可能将 state 拆分得太多了。您能否详细描述一下您希望如何合并和使用这两种状态? -
你有根 reducer 来组合你在 reduce 中所做的状态位置吗?
-
我相信我会。我应该只使用它还是有办法可以组合多个状态?
-
正如@DrewReese 指出的那样,您需要组合状态或另一种方法是将
activeConversation作为有效负载传递。这样你就可以在减速器内部做action.payload.activeConversation. -
我不一定想从 thunk 传递它,因为我需要知道
activeConversation在那个特定点的当前状态。我想知道是否有办法从我的减速器函数中访问activeConversation的状态(注意我已经导入了activeConversation减速器)。
标签: javascript reactjs redux react-redux redux-thunk