【发布时间】:2021-11-01 02:12:54
【问题描述】:
我正在尝试使用 @reduxjs/toolkit 和 typescript 调用 API 端点。
我按照这里的例子,没有成功https://redux-toolkit.js.org/api/createAsyncThunk
我遇到了一些打字错误,我做错了什么?
1°error:当我像在 MessageController.tsx 中那样进行调度时,打字稿说:
“AsyncThunk
2° 错误:在 message.slice.ts 中,每当我执行 message.fulfilled 或 denied 或 pending 时,我都会得到:
类型 '(data: any) => AsyncThunk
message.slice.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
);
MessageController.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)
【问题讨论】:
标签: reactjs typescript redux async-await redux-toolkit