reactjs - 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)
解决方案
案例1:你创造useAppDispatch
错了。更新可以是这样的:
export const useAppDispatch = useDispatch<AppDispatch>();
案例 2:您创建错误的 thunk 操作。你可以这样更新:
export const sendMessage = createAsyncThunk(
`message/sendMessage`,
async (data, thunkAPI) => {
...
推荐阅读
- google-apps-script - 有没有办法从电子表格中的联系人列表生成 gmail 草稿?
- html - VueJS 中递归组件的布局中断
- javascript - 跨选项卡/窗口存储数据但不持久
- reactjs - 在 React 中映射 graphQL 对象时出错
- jenkins - 如果 Jenkins 管道被 dockerized,如何在 docker 主机上执行单步或构建后操作?
- azure-cosmosdb - Cosmos DB 读取没有分区键的单个文档
- powershell - 尝试通过适用于 cmd 行的 Powershell 运行无头可执行命令
- ios - IOS:保存蒙版图像时,保存原始图像?
- javascript - 如何使用 jQuery 防止事件在特定父级的整个 DOM 树中被触发
- python - 将 DataFrame 转换为特定的字典格式