我有一个initialState和一个动态URL以及axios的异步形实转换
我想根据初始状态下的一个键来更改URL查询参数。
?query=${initialState.category}
类别更改,但URL获取类别未更改的数据(它使用初始键而不是修改的键)
const initialState = {
category: "burger",
products: [],
isLoading: true,
categories :{
burger:"burger",
kebab:"kebab",
chicken:"chicken",
pizza:"pizza",
fish:"fish",
vegan:"vegan",
salad:"salad",
pasta:"pasta",
steak:"steak",
dessert:"dessert",
waffle:"waffle"
}
};
const url = `https://api.spoonacular.com/food/menuItems/search?query=${initialState.category}&number=10&apiKey=API_KEY`;
export const getProducts = createAsyncThunk(
"products/getProducts",
async (_, thunkAPI) => {
try {
const response = await axios(url);
console.log(response);
return await response.data;
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message });
}
}
);
export const productSlice = createSlice({
name: "product",
initialState,
reducers: {
pickCategory: (state, action) => {
state.category = action.payload;
},
1条答案
按热度按时间cs7cruho1#
该行是静态,因为initialState中的值未发生变化:
您需要在getProductsThunk中移动该常量,因为thunk可以访问当前存储: