可能对API理解有问题,无法显示error message
来源:10-8 【redux-toolkit】sotre配置(configureStore)与异步处理(createAsyncThunk)

慕莱坞8640370
2021-10-23
现在的redux store是可以用的。进入rejected状态后无法显示error message
因为不会写mockAPI,所以用了fastAPI这个网站,这是我的API:链接描述
现在fullfilled的时候,createAsyncThunk返回了我的全部代API信息,error和data都有,我需要在fullfilled的代码中再添加一个data才能使用data的数据部分。
当我给我的API添加 {headers:{‘response-status’:‘400’}}的时候,返回状态为400,页面展示数据消失,仓库中的error为undefined,loading(pin):false data(pin): [ ] 状态为rejected (in redux dev tool):
slice:其实就是课堂代码换了个名字
interface categoriesState {
loading: boolean;
error: string | null;
data: any[];
}
const initialState: categoriesState ={
loading: true,
error: null,
data:[],
}
export const getCategories = createAsyncThunk(
'categories/getCategoreis',
async(parameters: {},thunkAPI)=> {
const {data}:any = await axios.get(
`https://www.fastmock.site/mock/456923cc3f54559b181a0f418788fccc/api/categories`,
// {headers:{'response-status':'400'}} 使用的fastAPI,添加这个状态码,就会返回400
)
return data;
}
)
export const categoriesSlice = createSlice({
name: "categories",
initialState,
reducers: {
},
extraReducers: {
[getCategories.pending.type]: (state) => {
state.loading = true;
},
[getCategories.fulfilled.type]: (state, action) => {
state.data = action.payload.data;
state.loading = false;
state.error = null;
},
[getCategories.rejected.type]: (state, action: PayloadAction<string | null>) => {
state.loading = false;
state.error = action.payload;
},
}
});```
component:
···
/**fetch data from store */
const categories = useSelector(s => s.categoreis.data);
const error = useSelector(s => s.categoreis.error);
const loading = useSelector(s => s.categoreis.loading);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getCategories({}))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
还有一个问题就是,我的createAsyncThunk不需要接受params,但是不写params又会报错,我只好传递了空对象,不知道有没有更好的解决方法。
crateAsyncThunk中:
export const getCategories = createAsyncThunk(
'categories/getCategoreis',
async(parameters: {},thunkAPI)
使用:
dispatch(getCategories({}))
2回答
-
我很容易上手
2022-01-14
promise 返回 data 或 undefined 都算是成功的 promise 吧,如果直接返回 axios.get() 的结果就是直接返回了 promise,那 extraReducers 应该就能正确捕获异常了
00 -
阿莱克斯刘
2021-10-24
第一个问题。可以在reject里面打印一下action的数据吗?听起来像是识别到了400、进入了reject,但没拿到响应数据。我们需要先确认reject里面action的内容
参数不能省略,否则方法签名无法匹配。没有参数就传个null应该也可以,"{}"的确有点难看
00
相似问题