我是非常新的RTK,所以我正在尝试创建一个商店和切片机。
首先,至少我想从一个API中获取一些数据,这样当它开始加载和成功后,我就知道它的状态。
我在这里创建切片机:
const initialState: PlayerState = {
players: [],
status: 'idle'
};
export const getPlayers = createAsyncThunk('players/getPlayers', async () => {
const response = await axios.get(
'https://6360055fca0fe3c21aaacc04.mockapi.io/player'
);
return response.data;
});
const playerSlice = createSlice({
name: 'players',
initialState,
reducers: {
addPlayer: (state, action: PayloadAction<IPlayerProps>) => {
console.log('done');
state.players.push(action.payload);
}
},
extraReducers: {
[getPlayers.pending]: (state, action) => {
console.log('loading');
state.status = 'loading';
},
[getPlayers.fulfilled]: (state, action) => {
console.log('succeeded');
state.status = 'succeeded';
state.players = state.players.concat(action.payload);
}
}
});
export const { addPlayer } = playerSlice.actions;
export const selectPlayers = (state: RootState) => state.players.payload;
现在我试着把它和商店联系起来:
//@ts-nocheck
import { configureStore } from '@reduxjs/toolkit'
import { addPlayer } from './playerSlice'
export const store = configureStore({
reducer: {
players: addPlayer,
},
})
export type RootState = ReturnType<typeof store.getState>;
所以,在那之后,我有一个页面与一个按钮,所以当我点击它,我试图调度的东西了,不幸的是没有运气:
const NextPage = () => {
const dispatch = useDispatch();
return (
<ButtonNext
onClick={() => {
dispatch(addPlayer);
}}
text="< Back"
/>
);
};
export default NextPage;
任何帮助都将不胜感激!:)
1条答案
按热度按时间ojsjcaue1#
代码中存在几个问题
首先修复您的
createAsyncThunk
您的切片应该如下所示,请注意以下情况的
builder
回调:在匿名fn中调用它
而且我也认为你们的
store
中的根减速器是不对的请使用工作示例检查此沙箱:https://codesandbox.io/s/redux-toolkit-basic-players-w-pokemons-6wmjm0?file=/src/features/playerSlice.js:409-995