首页 > 解决方案 > redux 工具包 createAsyncThunk 打字稿错误

问题描述

我正在尝试使用 @reduxjs/toolkit 和 typescript 调用 API 端点。

我已经按照这里的示例进行操作,但没有成功https://redux-toolkit.js.org/api/createAsyncThunk

我遇到了一些打字稿错误,我做错了什么?

1°错误:当我像在 MessageController.tsx 中那样进行调度时,打字稿说: 'AsyncThunk<any, void, {}>' 类型的参数不可分配给'AnyAction' 类型的参数。类型 'AsyncThunk<any, void, {}>' 中缺少属性 'type' 但在类型 'AnyAction'.ts(2345) index.d.ts(19, 3) 中是必需的:此处声明了 'type'。

2° 错误:在 message.slice.ts 中,每次我执行 message.fulfilled 或拒绝或挂起时,我都会得到: Property 'fulfilled' does not exist on type '(data: any) => AsyncThunk<any, void, {} >'.ts(2339)

消息切片.ts

export const sendMessage = ( data) =>createAsyncThunk(
    `message/sendMessage`,
    async (data, thunkAPI) => {
        const response = await axios.post
        ( `/api/v1/xxx/test-messages`,
        data,
        httpOptions(getDefaultHeaders()));

       return response.data;
      }
    )
    
    
    
    const messageSlice = createSlice({
    name: "message",
    initialState: {
       message: {},
       loading: "idle",
       error: "",
    },
    reducers: {},
    extraReducers: (builder) => {
       builder.addCase(sendMessage.pending, (state) => {
         state.message = {};
           state.loading = "loading";
       });
       builder.addCase(
        sendMessage.fulfilled, (state, { payload }) => {
             state.message = payload;
             state.loading = "loaded";
       });
       builder.addCase(
        sendMessage.rejected,(state, action) => {
             state.loading = "error";
             state.error = action.error.message;
       });
    }
  })
  
  interface stateI{
  message: messageI;
}
interface messageI{
  loading: string;
}

  export const selectMessage = createSelector(
    (state: stateI) => ({
       message: state.message,
       loading: state.message.loading,
    }), (state) =>  state
  );

消息控制器.tsx


  import {useAppDispatch} from '../../state/store';

  const dispatch = useAppDispatch();

  const { message } = useSelector(selectMessage);
    React.useEffect(() => {
     console.log(message)
     // TODO display the result of the api call in the page..
  }, [message]); 
  
  const handleClick =()=>{
    const data = {
      "environment": dropboxValue,
      "payload": textareaValue
    };

    dispatch(sendMessage(data))
    .then(() => {
      // TODO display the result of the api call in the page..
    })

  }
  
   //additional ui code for a button which when clicked trigger the api call (sendMessage)


store.ts

export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
//other code not relevant (I think)

标签: reactjstypescriptreduxasync-awaitredux-toolkit

解决方案


案例1:你创造useAppDispatch错了。更新可以是这样的:

export const useAppDispatch = useDispatch<AppDispatch>();

案例 2:您创建错误的 thunk 操作。你可以这样更新:

export const sendMessage = createAsyncThunk(
    `message/sendMessage`,
    async (data, thunkAPI) => {
    ...

推荐阅读