首页 > 解决方案 > 将套接字添加到 redux 会导致序列化警告

问题描述

这是我的代码:

export const Wrapper = ({ children }) => {
  const authState = useAppSelector((state) => state.auth);
  const dispatch = useAppDispatch();
  const { clientsState, setClientsState } = useContext(ClientsContext);

  const token = getAuthenticationToken();

  // Configure socket
  useEffect(() => {
    if (authState.socket) return;
    const socket: SocketIOClient.Socket = WebsocketClient.connect('...', token);
    dispatch(setAuthState({ ...authState, socket, isAuthenticated: true }));
  });
});

authSlice.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { IAuthState } from '../../types';

const initialState: IAuthState = {
  isAuthenticated: false,
  profile: null,
  socket: null,
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setAuthState(state, action: PayloadAction<IAuthState>) {
      state = action.payload;
    },
  },
});

export const { setAuthState } = authSlice.actions;
export const authReducer = authSlice.reducer;

我正在尝试将套接字传递给 redux,因为稍后我需要在其上调用各种方法。但是当我这样做时,我得到了这个错误:

A non-serializable value was detected in an action, in the path: `payload.socket`. Value: 
Object { io: {…}, nsp: "/", json: {…}, ids: 0, acks: {}, receiveBuffer: [], sendBuffer: [], connected: false, disconnected: true, flags: {}, … }
 
Take a look at the logic that dispatched this action:  
Object { type: "auth/setAuthState", payload: {…} }
 
(See https://redux.js.org/faq/actions#why-should-type-be-a-string…t-least-serializable-why-should-my-action-types-be-constants) 
(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)

我明白。它把我引到这里,解释是有道理的。我需要在商店配置中添加一个例外。

我的问题是我该怎么做?我从哪里得到这些数据?

configureStore({
  //...
  middleware: getDefaultMiddleware({
    serializableCheck: {
      // Ignore these action types
      ignoredActions: ['your/action/type'],
      // Ignore these field paths in all actions
      ignoredActionPaths: ['meta.arg', 'payload.timestamp'],
      // Ignore these paths in the state
      ignoredPaths: ['items.dates'],
    },
  }),
}) // from docs

标签: javascriptreactjstypescriptreduxsocket.io

解决方案


推荐阅读