【问题标题】:Why is there an error on createSlice when the initial state is null?为什么初始状态为 null 时 createSlice 会出错?
【发布时间】:2020-11-12 04:00:43
【问题描述】:
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppInfo } from '../models';

const initialState: AppInfo | null = null;

const appSlice = createSlice({
  name: 'app',
  initialState,
  reducers: {
    selectApp(state, action: PayloadAction<AppInfo>) {
      return action.payload;
    },
  },
});

export const { selectApp } = appSlice.actions;
export default appSlice.reducer;

// models.ts
export type AppInfo = {
  appName: string;
  createDate: string;
  develop: string;
  op: string;
};

我希望在 redux 启动时 state.appnull,但稍后允许用户选择应用程序。但是,我在减速器selectApp 上遇到了很长的 TypeScript 错误。这个错误是什么意思?

(method) selectApp(state: null, action: PayloadAction<AppInfo>): AppInfo
Type '(state: null, action: { payload: AppInfo; type: string; }) => AppInfo' is not assignable to type 'CaseReducer<null, { payload: any; type: string; }> | CaseReducerWithPrepare<null, PayloadAction<any, string, any, any>>'.
Type '(state: null, action: { payload: AppInfo; type: string; }) => AppInfo' is not assignable to type 'CaseReducer<null, { payload: any; type: string; }>'.
Type 'AppInfo' is not assignable to type 'void'.ts(2322)

【问题讨论】:

    标签: reactjs typescript redux redux-toolkit


    【解决方案1】:

    https://www.reddit.com/r/reduxjs/comments/guns93/nullable_state_best_practice_typescript_redux/

    export type AuthState = AppInfo | null;
    
    const initialState = null as AuthState; 
    

    我在 reddit 帖子中找到了答案。似乎null 将使打字稿将类型缩小为null 而不是AppInfo | null。使用as可以解决问题。

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多