在Redux工具包中创建动态URL

cnwbcb6i  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个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;
    },
cs7cruho

cs7cruho1#

该行是静态,因为initialState中的值未发生变化:

const url = `https://api.spoonacular.com/food/menuItems/search?query=${initialState.category}&number=10&apiKey=API_KEY`;

您需要在getProductsThunk中移动该常量,因为thunk可以访问当前存储:

...
async (_, thunkAPI) => { 
 const {category} = thunkApi.getState()
 const url = `https://api.spoonacular.com/food/menuItems/search? 
  query=${category}&number=10&apiKey=API_KEY`;
}
...

相关问题