WritableDraft 类型上不存在属性“user”

问题描述 投票:0回答:1

我有一个 redux userSlice 正在尝试从商店获取用户数据。

客户端/src/redux/features/userSlice.ts

import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { User } from "../../interfaces/user";
import userApi from "../../apis/user";

export const getUser = createAsyncThunk("user/getUser", async (_, thunkApi) => {
  try {
    const response = await userApi.getUser();
    return response;
  } catch (error) {
    throw thunkApi.rejectWithValue({ error: "user not initialized" });
  }
});

const userSlice = createSlice({
  name: "user",
  initialState: {
    profile: {
      ipAddress: "",
    },
  },
  reducers: {
    getUser: (state, action: PayloadAction<User>) => {
      state.user = action.payload;
    },
  },
});

export const { getUser: getUserAction } = userSlice.actions;
export default userSlice.reducer;

我能够在API接口中成功注销用户:

客户端/src/apis/user.ts

const userApi = {
  getUser: async () => {
    try {
      const response = await fetch("http://localhost:5000/user/:ipAddress");
      const user = await response.json();
      console.log("in user api:", user);
      return user;
    } catch (error) {
      console.error("Error fetching user:", error);
      return error;
    }
  },
};

export default userApi;

console.log("in user api:", user);
返回以下内容:

in user api: 
Object { user: {…} }
​
user: Object { _id: "65c1f831b5759dc19442396d", ipAddress: "::ffff:127.0.0.1", createdAt: "2024-02-06T09:13:21.391Z", … }
​
<prototype>: Object { … }

但是,我在

state.user = action.payload
上看到一个错误,其中指出
Property 'user' does not exist on type 'WritableDraft<{ profile: { ipAddress: string; }; }>'

我定义的用户类型如下:

客户端/src/interfaces/user.ts

export type User = {
  profile: UserProfile
}

export type UserProfile = {
  ipAddress: string
}

export type UserState = {
  user: User
}

我的 redux 状态仅显示已满足的初始状态,而不是预期的用户 ipAddress。

typescript api redux slice
1个回答
0
投票

问题似乎出在您的

WritableDraft
界面上。您能否更新您的问题以包含该接口定义?也许您将
WritableDraft
profile
属性与
user
属性混为一谈?

考虑以下更改:

const userSlice = createSlice({
  name: "user",
  initialState: {
    profile: {
      ipAddress: "",
    },
  },
  reducers: {
    getUser: (state, action: PayloadAction<User>) => {
      // This is the change here, note that your initial state has a
      // profile not a user
      state.profile = action.payload;
    },
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.