我想在調度時從 redux 工具包的 createAsyncThunk 接收資料。
但我不知道如何設定資料型別。
如果未指定資料型別,則會顯示一條帶有紅線的警告線。
像這樣的截圖
如何指定型別?
這是我的代碼
// commentinput is string and post.id is number
const commetsubmitfun = useCallback(() => {
dispatch(addComment({content: commentinput, postId: post.id}));
}, [dispatch, commentinput]);
export const addComment = createAsyncThunk(
'post/addComment',
async (data, {rejectWithValue}) => {
try {
// data: {content: "aaa", postId: 66}
const response = await axios.post(`/post/${data.postId}/comment`, data); // POST /post/1/comment
return response.data;
} catch (error: any) {
return rejectWithValue(error.response.data);
}
},
);
uj5u.com熱心網友回復:
您應該在呼叫時宣告型別createAsyncThunk
,宣告這樣的介面data
:
type DataType = {
content : string
postId : string
}
然后在此處添加:
async (data : DataType, {rejectWithValue}) => {
你可以在這里閱讀更多內容:https ://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
uj5u.com熱心網友回復:
您可以使用 interface 或 type 在 createSlice 檔案中指定型別
例如:
interface Action {
type: string
payload: {
img: string
images: string[] | [] | null
}
}
type 總是字串,payload 就是你放在 { } 里面的內容dispatch(addComment({content: ...payload, postId: ..payload}));
interface Action {
type: string
payload: {
content: string
postId: number //or if its possibly undefined/null postId?: number | null | undefined
}
}
const initialStateValue = {
post: null
}
reducers: {
addComment: (state: any = initialStateValue, action: Action) => {
state.post = action.payload;
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468392.html
標籤:javascript 反应 打字稿 反应式
上一篇:如何重置所有輸入欄位的反應?
下一篇:如何從字串中洗掉陣列?