簡體   English   中英

如何修復 redux-toolkit 中的 typescript 錯誤?

[英]How to fix typescript error in redux-toolkit?

我正在用 typescript 做一個 redux-toolkit 教程。 但我是 typescript 初學者。

我不知道這里有什么問題。 請給我你的見解。

這是一條錯誤消息。 TS2322:類型“數字”不可分配給類型“無效|” State | 可寫草稿”。

import {CaseReducer, createSlice, PayloadAction} from "@reduxjs/toolkit";

type State = {
  value: number
}
const increment: CaseReducer<State,PayloadAction<number>> = (state, action) => state.value + action.payload; // error line

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment,
    decrement: state => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
})

export const {increment, decrement, incrementByAmount} = counterSlice.actions;

export default counterSlice.reducer;

沒有花括號的箭頭 function 是隱含的 return 所以你返回state.value + action.payload這是一個number

Redux Toolkit allows you to either return a new state (type State | WritableDraft<State> ) or modify the draft state and not return anything (type void ). 您會收到 Typescript 錯誤,因為返回的number既不是也不是這些。

您可能想要修改草案 state,因此您需要在 function 主體周圍使用花括號,這樣您就不會返回任何內容。


這三個函數都是有效的。 從最詳細到最詳細排序:

  1. 您可以使用加法賦值運算符+=直接增加值
const increment: CaseReducer<State,PayloadAction<number>> = (state, action) => {
  state.value += action.payload;
}
  1. 您可以使用賦值運算符=state.value屬性分配一個新值 =
const increment: CaseReducer<State,PayloadAction<number>> = (state, action) => {
  state.value = state.value + action.payload;
}
  1. (不推薦)您可以退回全新的 state。 我在花括號周圍使用括號來返回具有屬性value 的 object
const increment: CaseReducer<State,PayloadAction<number>> = (state, action) => ({
  value: state.value + action.payload
});

如果存在value以外的屬性,則需要復制它們,例如{...state, value: newValue } ,這是您在傳統 Redux 減速器中看到的。 Redux Toolkit 使選項 1 和 2 可用,因此您不必這樣做。 但如果您選擇退回新的 state,那么它必須是完整的 state。

CaseReducer返回值必須為void | State | WritableDraft void | State | WritableDraft void | State | WritableDraft而你的表達:

(state, action) => state.value + action.payload

是一個返回數字的 function。 解決方案是在返回值前添加void運算符,將其設置為undefined

(state, action) => void (state.value += action.payload)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM