【发布时间】:2021-10-29 13:26:50
【问题描述】:
我正在使用 reducer 在 Redux 中设置状态。我的状态目前看起来像这样。
{
activeConversation: "Jim"
conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
user: {id: 8, username: "josh", email: ""}
}
在我的旧减速器中,我只是获取对话数组并进行设置,但现在我还需要访问 activeConversation 字符串。因此,我决定使用我的根减速器,它结合了所有内容,以便它可以正常工作。这是我的根减速器。
import { createStore, applyMiddleware, combineReducers } from "redux";
import loggerMiddleware from "redux-logger";
import thunkMiddleware from "redux-thunk";
import user from "./user";
import conversations from "./conversations";
import activeConversation from "./activeConversation";
import {
addMessageToStore,
} from "./utils/reducerFunctions";
const CLEAR_ON_LOGOUT = "CLEAR_ON_LOGOUT";
const SET_MESSAGE = "SET_MESSAGE";
export const clearOnLogout = () => {
return {
type: CLEAR_ON_LOGOUT
};
};
export const setNewMessage = (message, sender) => {
return {
type: SET_MESSAGE,
payload: { message, sender: sender || null },
};
};
const appReducer = combineReducers({
user,
conversations,
activeConversation
});
const rootReducer = (state, action) => {
if (action.type === CLEAR_ON_LOGOUT) {
state = undefined;
} else if (action.type === SET_MESSAGE) {
return addMessageToStore(state, action.payload);
}
return appReducer(state, action);
};
export default createStore(rootReducer, applyMiddleware(thunkMiddleware, loggerMiddleware));
我的 setNewMessage 函数被调用,然后调用addMessageToStore。
export const addMessageToStore = (state, payload) => {
const { message, sender } = payload;
return { ...state, conversations: state.conversations.map((convo) => {
if (convo.id === message.conversationId) {
const newUnread = convo.unreadMessages;
if (state.activeConversation === convo.otherUser) {
newUnread = (parseInt(newUnread) + 1).toString();
}
const newConvo = {
...convo,
messages: convo.messages.concat(message),
latestMessageText: convo.latestMessageText,
unreadMessages: newUnread
}
console.log("newConvo:", {...state, conversations: newConvo});
return {...state, conversations: newConvo};
} else {
return {...state, conversations: convo};
}
})};
};
问题在于next state 没有更新。当它返回next state 时,它只显示以前的状态而不是我的新状态。有谁知道怎么回事?
【问题讨论】:
标签: javascript reactjs redux react-redux state