如何在Redux中从API重新加载数据

s71maibg  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(124)

当我在hangman中丢失时,我想在API中重新加载我的数据,这样一个新的密码就会出现。不幸的是,我不知道如何在不重新加载整个页面的情况下重新加载它,例如,在单击按钮时再次运行API是否可能?

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

const url = 'https://random-word-api.herokuapp.com/word?number=1';

const initialState = {
    password: '1',
    misstake: 0,
    usedChart: [],
};

export const getPassword = createAsyncThunk(
    'hangman/getPassword',
    async (thunkAPI) => {
        console.log(1)
        try {
            const resp = await axios(url)
            return resp.data
        } catch(error){
            return thunkAPI.rejectWithValue('api not working');
        }
    }
);

const HangManSlice = createSlice({
    name: 'hangman',
    initialState,
    reducers: {
        increaseError: (state) => {
            state.misstake += 1
        },
        usedCharts: (state, action) => {
            state.usedChart.push(action.payload)
        },
        restart: (state) => {
            state.misstake = 0
            state.usedChart = []
            getPassword()
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getPassword.fulfilled, (state, action) => {
                state.password = action.payload;
            })
    }
})

export const { increaseError, usedCharts, restart } = HangManSlice.actions

export default HangManSlice.reducer
gkn4icbw

gkn4icbw1#

您应该从“restart”按钮处理程序调度getPassword(),而不是将其称为reducer。

const RestartButton = () => {
  const dispatch = useDispatch();

  const restartHandler = () => {
    dispatch(getPassword());
    dispatch(restart())
  };
 
  return (
    <button onClick={restartHandler}>Restart</button>
  );
}

另一个选择是使用getPassword thunk初始化一个新游戏,如下所示:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

const url = 'https://random-word-api.herokuapp.com/word?number=1';

const initialState = {
    loading: false,
    password: '1',
    misstake: 0,
    usedChart: [],
};

export const startGame = createAsyncThunk(
    'hangman/getPassword',
    async (thunkAPI) => {
        console.log(1)
        try {
            const resp = await axios(url)
            return resp.data
        } catch(error){
            return thunkAPI.rejectWithValue('api not working');
        }
    }
);

const HangManSlice = createSlice({
    name: 'hangman',
    initialState,
    reducers: {
        increaseError: (state) => {
            state.misstake += 1
        },
        usedCharts: (state, action) => {
            state.usedChart.push(action.payload)
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(startGame.pending, (state, action) => {
                state.loading = true;
            })
            .addCase(startGame.rejected, (state, action) => {
                state.loading = false;
            })
            .addCase(startGame.fulfilled, (state, action) => {
                state.loading = false;

                // store new password
                state.password = action.payload;

                // reset state
                state.misstake = 0
                state.usedChart = []
            })
    }
})

export const { increaseError, usedCharts, restart } = HangManSlice.actions

export default HangManSlice.reducer

现在您可以分派startGame(),状态将使用新密码重置。

相关问题