Igg*_* Xy 4 typescript redux redux-toolkit
我刚开始使用 typescript 和 redux 工具包,并且遇到了 addCase 不存在于我的 extraReducers 中的构建器回调函数上的问题。我在网上没有看到任何与我类似的情况,并且怀疑我错过了一些非常简单的东西。不过,我似乎找不到它。
这是我的 createAsyncThunk:
type myData = object[]
export const fetchResults = createAsyncThunk
(
"search/fetchResults", async (searchTerm: string) => {
try {
const url:string = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}keyes&key=${process.env.REACT_APP_MY_API_KEY}`
const response = await axios.get(url);//where you want to fetch data
return (await response.data()) as myData;
} catch (error) {
return error
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的 extraReducers 切片:
interface searchInterface {
field: string
result: object[]
loading: 'idle' | 'loading' | 'loaded' | 'failed'
}
const initialState: searchInterface = {
field: "",
result: [],
loading:"idle"
}
const searchSlice = createSlice({
name: 'search',
initialState,
reducers: {
fieldChange(state, action: PayloadAction<string>)
{
state.field = action.payload
},
extraReducers: (builder) => {
builder.addCase(fetchResults.pending, (state: searchInterface) => {
state.result = [];
state.loading = "loading";
});
builder.addCase(
fetchResults.fulfilled, (state: searchInterface, action:PayloadAction<object[]>) => {
state.result = action.payload;
state.loading = "loaded";
});
builder.addCase(
fetchResults.rejected, (state: searchInterface) => {
state.loading = "failed";
});
}
}
})
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?
han*_*ojg 12
extraReducers您将代码示例中的放置在reducers对象内。把它放在外面,改成:
const searchSlice = createSlice({
name: 'search',
initialState,
reducers: {
fieldChange(state, action: PayloadAction<string>)
{
state.field = action.payload
},
}, // Notice the closed curly bracket here
extraReducers: (builder) => {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2886 次 |
| 最近记录: |