代码之家  ›  专栏  ›  技术社区  ›  user15322469

如何在Redux工具箱中设置typescript?

  •  1
  • user15322469  · 技术社区  · 4 年前

    我想在发送时从redux toolkit的CreateAynchThunk接收数据。

    但我不知道如何设置数据类型。

    如果未指定数据类型,则会显示一条带有红线的警告线。

    就像这个截图

    enter image description here

    如何指定类型?

    这是我的密码

        // 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);
            }
          },
        );
    
    2 回复  |  直到 4 年前
        1
  •  1
  •   Khalfoun Mohamed El Mehdi    4 年前

    调用时应该声明类型 createAsyncThunk , 为声明一个接口 data 这样地:

    type DataType = { 
       content : string
       postId : string
    }
    

    然后添加到这里:

          async (data : DataType, {rejectWithValue}) => {
    

    你可以在这里阅读更多内容: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk

        2
  •  0
  •   codmitu    4 年前

    您可以使用接口或类型在createSlice文件中指定类型

    如:

    interface Action {
        type: string
        payload: {
           img: string
           images: string[] | [] | null
        }
    }
    

    类型始终是字符串,有效负载是您在{}中放入的内容 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;
        },