Typescript错误-ReduxJS Toolkit中函数参数'state'的属性赋值

gwo2fgha  于 2022-11-24  发布在  TypeScript
关注(0)|答案(3)|浏览(142)

这是我的密码-

type LoginState = {
  loading: 'idle' | 'pending' | 'succeeded' | 'failed';
  role: string;
  error: string;
};

const initialState: LoginState = {
  loading: 'idle',
  role: '',
  error: '',
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(authUser.pending, (state: LoginState) => {
        state.loading = 'pending';
      })
      .addCase(authUser.rejected, (state, action) => {
        state.loading = 'failed';
        console.log('action', action);
      });
  },
});

我在TS上看到这个错误-

我不是很确定,我如何才能解决这个问题。我已经添加了接口,但似乎我缺少了一些东西。
你们能帮忙吗。

csga3l58

csga3l581#

这是由您在项目中设置/配置的一个去毛刺规则引起的。您可以完全禁用该规则(* 不推荐 *),或者在一些有意义的地方覆盖该规则,比如在reducer函数中,您 * 正在 * 直接设置state对象的属性。在下一行代码中添加一个注解来禁用特定的规则。
示例:

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(authUser.pending, (state: LoginState) => {
        // eslint-disable-next-line no-param-reassign
        state.loading = 'pending';
      })
      .addCase(authUser.rejected, (state, action) => {
        // eslint-disable-next-line no-param-reassign
        state.loading = 'failed';
      });
  },
});
vptzau2j

vptzau2j2#

我需要在.eslintrc中禁用此规则,以支持状态中的分配

'no-param-reassign': ['error', {
  props: true,
  ignorePropertyModificationsFor: [
    'state',
  ]
}],
ukqbszuj

ukqbszuj3#

不要声明状态的类型。拥有的库应该正确地将其类型为WritableDraft<LoginState>(它使用initialState处提供的类型):

.addCase(authUser.pending, (state) => {
        state.loading = 'pending';
      })

相关问题