使用Tauri+React+Redux开发聊天应用遇类型错误求助
问题解决:Redux Toolkit中
Property 'app' does not exist on type 'WritableDraft<{ channelId: null; channelName: null; }>'错误 错误根源
你在appSlice的setChannelId reducer里错误尝试访问state.app,但该slice的state本身就是{channelId: null, channelName: null}——因为在store.ts中,根状态的app字段对应的就是appReducer,所以slice内部的state不需要额外嵌套app属性。
当你手动添加app: null到initialState后,根状态的结构变成了state.app.app,导致你的selector(state.app.channelId)实际取的是错误路径,最终引发应用无法渲染的问题。
修复步骤
1. 修正appSlice的reducer逻辑
把setChannelId里的错误代码改成直接修改channelId(另外注意你误用了+=,设置ID应该是赋值操作):
import { PayloadAction, createSlice } from '@reduxjs/toolkit'; import type { RootState } from '../app/store'; // 给state定义明确类型,避免模糊类型问题 interface AppState { channelId: string | null; channelName: string | null; } export const appSlice = createSlice({ name: 'app', initialState: { channelId: null, channelName: null, } as AppState, reducers: { setChannelId: (state, action: PayloadAction<string>) => { // 直接修改state的channelId字段 state.channelId = action.payload; }, // 若需要设置频道名称,可添加对应reducer setChannelName: (state, action: PayloadAction<string>) => { state.channelName = action.payload; } }, }); export const { setChannelId, setChannelName } = appSlice.actions; export const selectChannelId = (state: RootState) => state.app.channelId; export const selectChannelName = (state: RootState) => state.app.channelName; export default appSlice.reducer;
2. 移除initialState中的app: null
恢复initialState的原始结构,不需要额外的app嵌套字段。
3. 验证根状态结构
你的store.ts配置是正确的:
export const store = configureStore({ reducer: { user: userReducer, app: appReducer, // 根状态的app字段对应appSlice的状态 } });
此时根状态的结构为:
{ user: UserState, app: { channelId: string | null, channelName: string | null } }
你的selector(state.app.channelId)完全匹配这个结构,能正确获取对应值。
额外建议
- 给slice的state定义明确的TypeScript接口,避免
null带来的类型模糊问题 - 确保reducer中的操作符合业务逻辑:设置ID用赋值
=而非累加+=
内容的提问来源于stack exchange,提问作者Boontjes
相关产品推荐
相关产品推荐

