reactjs - 类型“ThunkAction”上不存在属性“then”
问题描述
我收到错误
Property 'then' does not exist on type 'ThunkAction<Promise<string>
我正在尝试从我的切片中的 AppThunk 返回一个承诺。
下面是我设置的代码,我经历了几个相同的问题,并遵循了那里给出的一些建议,但仍然无法弄清楚出了什么问题。
store.ts
import { configureStore, Action } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import { ThunkAction } from 'redux-thunk'
import rootReducer, { RootState } from './rootReducer'
const store = configureStore({
reducer: rootReducer
})
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('./rootReducer', () => {
const newRootReducer = require('./rootReducer').default
store.replaceReducer(newRootReducer)
})
}
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>
export default store
我的切片.ts
import { AppThunk } from 'app/store'
// ...
// my reducer logic is here
// ...
export const fetchIssuePromise = (): AppThunk<Promise<string>> => async (dispatch) => {
return Promise.resolve("string")
}
我在我的组件中使用它。
我的组件.tsx
import React, { useEffect } from 'react'
import { fetchIssue, fetchIssuePromise } from 'features/mySlice.ts'
import { useDispatch } from 'react-redux'
export const MyComponent = ({
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchIssuePromise()).then(() => {
// My logic here.
})
}, [dispatch])
})
我知道我可以通过存储在 redux 状态并使用选择器来实现这一点。但我不想在 redux 中存储一些数据,尤其是来自服务器的验证错误。
我不确定这种方法是否正确,请让我知道如何处理此问题或任何更好的方法来实现此目标。
解决方案
不要使用默认的“useDispatch”钩子。
正如这个 github 问题中提到的:https ://github.com/reduxjs/redux-toolkit/issues/678
链接文档:https ://redux-toolkit.js.org/usage/usage-with-typescript#getting-the-dispatch-type
在您的 store.ts 中:
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
在您的 Component.tsx 中:
const dispatch = useAppDispatch() // hook exported from store
推荐阅读
- sql - 收到错误“无法嵌套 INSERT EXEC 语句”
- pandas - 在 Python 中处理一个巨大的文件(>30GB)
- javascript - 有没有办法使用@click (v-on:click) 打开一个模式,同时关闭第二个模式(已经打开?)
- powershell - Windows $env:path ="$($env:path);." 它是在哪里添加的?
- c# - Azure 密钥管理 API [功能键]
- android - 通过 Knox SDK 从 Android 10 上的手机中提取 IMEI
- xamarin.android - 在 APK 外复制数据库
- yaml - 在另一个 yaml 文件中引用 yaml 中的嵌套列表
- c++ - 保持 MQTT 主题的消息排序
- graphql - 是否可以将动态类型的数据发送到 GraphQL,或者修改现有模式?