当我在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
1条答案
按热度按时间gkn4icbw1#
您应该从“restart”按钮处理程序调度
getPassword()
,而不是将其称为reducer。另一个选择是使用
getPassword
thunk初始化一个新游戏,如下所示:现在您可以分派
startGame()
,状态将使用新密码重置。