如何在 react typescript 中创建 redux store

How to make redux store in react typescript

我想用 typescript 做一个 react redux 但出错了。我使用 cra redux typescript 模板进行安装。我删除了 counter reducer 和一个使用 slice 的新 reducer。

我想指出我的错误是在 userSlice.ts 的 initialState 中,并出现以下错误。

这里是type.ts

export interface ExplicitContent {
  filter_enabled: boolean;
  filter_locked: boolean;
}

export interface ExternalUrls {
  spotify: string;
}

export interface Followers {
  href?: any;
  total: number;
}

export default interface UserType {
  country: string;
  display_name: string;
  explicit_content: ExplicitContent;
  external_urls: ExternalUrls;
  followers: Followers;
  href: string;
  id: string;
  images: any[];
  product: string;
  type: string;
  uri: string;
}

这里是userSlice.ts

import { createSlice } from '@reduxjs/toolkit';
import UserType from '../../types/user';

interface UserState {
  user: UserType;
  token: string;
}

const initialState: UserState= {
  user: null,
  token: '',
};

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setToken(state, action) {
      return {
        ...state,
        token: action.payload,
      };
    },
    setUser(state, action) {
      return {
        ...state,
        user: action.payload,
      };
    },
  },
});

我不知道我的 reducer 或 initialstate 是语法错误还是什么的。我使用 json2ts.com 来更改 api 调用的 json 响应,所以我认为这没有问题。但是我不确定我在 reducer 中的代码。请给我解决方案,提前谢谢你。

#note:我没有更改模板中关于 hooks.ts 和 store.ts 的任何内容,除了配置存储以导入我的减速器。

initialState 变量需要为 UserState。此外,UserState 中的 user 属性 目前不能为 null,因此您必须为其添加一个 null 联合类型,以便 initialState 有效。

interface UserState {
  user: UserType | null;
  token: string;
}
const initialState: UserType = {
  user: null,
  token: '',
};