[英]How do I set up typescript in Redux toolkit?
I want to receive data from redux toolkit's createAsyncThunk when dispatching.我想在调度时从 redux 工具包的 createAsyncThunk 接收数据。
But I don't know how to set the data type.但是我不知道如何设置数据类型。
If no data type is specified, a warning line is displayed with a red line.如果未指定数据类型,则显示一条带有红线的警告线。
like this Screenshot喜欢这个截图
How do I specify the type?如何指定类型?
this is my code这是我的代码
// 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);
}
},
);
You should declare type when calling createAsyncThunk
, declare an interface for data
like this:您应该在调用createAsyncThunk
时声明类型,为data
声明一个接口,如下所示:
type DataType = {
content : string
postId : string
}
then add it here:然后在此处添加:
async (data : DataType, {rejectWithValue}) => {
You can read more here: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk您可以在这里阅读更多内容: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
you specify the types in the createSlice file with either interface or type您使用接口或类型在 createSlice 文件中指定类型
eg:例如:
interface Action {
type: string
payload: {
img: string
images: string[] | [] | null
}
}
type is always string, payload is what you put in the { } inside dispatch(addComment({content: ...payload, postId: ..payload}));
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;
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.