使用Redux RTK获取数据-观察状态

nwnhqdif  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(164)

我是非常新的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;

任何帮助都将不胜感激!:)

ojsjcaue

ojsjcaue1#

代码中存在几个问题
首先修复您的createAsyncThunk

export const getPlayers = createAsyncThunk('players/getPlayers'
  async (_unusedArgs, _thunkApi) => {
    const response = await fetch('http://localhost:3000/players')
    return response.json()
  }
)

您的切片应该如下所示,请注意以下情况的builder回调:

export const playerSlice = createSlice({
  name: "players",
  initialState,
  reducers: {
    addPlayer: (state, action) => {
      console.log("done");
      state.players.push(action.payload);
    }
  },
  extraReducers: (builder) => {
    builder.addCase(getPlayers.fulfilled, (state, action) => {
      console.log(action.payload);
      state.players = action.payload;
      state.status = "idle";
    });
    builder.addCase(getPlayers.pending, (state, action) => {
      console.log("loading");
      state.status = "loading";
    });
  }
});

export default playerSlice.reducer;

在匿名fn中调用它

<ButtonNext
    onClick={() => {
      dispatch(getPlayers()); // call with no arguments.
    }}
    text="< Back"
  />

而且我也认为你们的store中的根减速器是不对的

import playerSlice from './playerSlice' // defaulted export

export const store = configureStore({
  reducer: {
    players: playerSlice,
  },
})

请使用工作示例检查此沙箱:https://codesandbox.io/s/redux-toolkit-basic-players-w-pokemons-6wmjm0?file=/src/features/playerSlice.js:409-995

相关问题