我正在Redux网站上学习Redux教程,在使用联合收割机减速器时遇到困难。如果我在不使用联合收割机减速器的情况下运行代码,它运行得很好。我一把单个减速器放入组合减速器的功能中。我得到这个:错误:";减速器";是必需的参数,并且必须是一个函数或可以传递给组合Reducers的函数对象。我做错了什么?
以下是使用联合收割机减速器前的商店:
import { configureStore } from "@reduxjs/toolkit";
import CoinsAllReducer from "./slices/CoinsAll";
export const store = configureStore({
reducer: {
coinsAll: CoinsAllReducer,
},
});
这是切片:
import axios from "axios";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const initialState = {
coinsAll: [],
status: "idle",
error: null,
};
export const fetchAllCoins = createAsyncThunk(
"coinsAll/fetchAllCoins",
async () => {
const res = await axios.get(
`https://api.coingecko.com/api/v3/coins/markets/?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false`
);
return res.data;
}
);
export const coinsAll = createSlice({
name: "coinsAll",
initialState,
reducers: {},
extraReducers(builder) {
builder
.addCase(fetchAllCoins.pending, (state) => {
state.status = "loading";
})
.addCase(fetchAllCoins.fulfilled, (state, action) => {
state.status = "succeeded";
state.coinsAll = action.payload;
})
.addCase(fetchAllCoins.rejected, (state, action) => {
state.status = "failed";
state.error = action.error.message;
});
},
});
export const selectCoinsAll = (state) => state.coinsAll.coinsAll;
export const selectStatus = (state) => state.coinsAll.status;
export default coinsAll.reducer;
上面的代码起作用,并从端点获取数据。
这里是商店修改为使用组合减速器:
import { configureStore } from "@reduxjs/toolkit";
import reducer from "./rootReducer";
export const store = configureStore(reducer);
这是rootReducer:
import { combineReducers } from "redux";
import coinsAllReducer from "./slices/coinsAll";
const reducer = combineReducers({
coinsAll: coinsAllReducer,
});
export default reducer;
我在切片上什么也没改。任何帮助都将不胜感激,谢谢。
configureStore
使用reducer
键获取对象。
应该是
export const store = configureStore({
reducer, // <-- object shorthand for the imported root reducer
// other configurations, etc...
});
您必须将配置对象内的组合reducer
传递给configureStore
方法
export const store = configureStore({
reducer:combinedReducer
});
因此,您更新的代码应该是
import { configureStore } from "@reduxjs/toolkit";
import reducer from "./rootReducer";
export const store = configureStore({reducer:reducer});
由于密钥和值是相同的,您可以简单地使用
import { configureStore } from "@reduxjs/toolkit";
import reducer from "./rootReducer";
export const store = configureStore({reducer});