我正在使用免费的电子商务 API 来获取数据,并且我的
getProducts
操作正在 products.jsx 中运行。当我 console.log(response)
这是工作,但我无法使用 useSelector
从 products.jsx 获取数据。
我认为我的
extraReducers
不起作用,因为我无法从产品中获取数据。
home.jsx
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { getProducts } from "../redux/products";
import Card from "../components/card";
function home() {
const dispatch = useDispatch();
const data = useSelector();
console.log("data");
// const [arr, setArr] = useState([]);
// console.log(arr);
// useEffect(async () => {
// const response = await dispatch(getProducts());
// setArr(response.payload.data);
// }, []);
useEffect(() => {
dispatch(getProducts());
}, [dispatch]);
return (
<div className="home">
{/* {arr.map((data) => {
return (
<>
<Card
title={data.title}
price={data.price}
img={data.images[0]}
></Card>
</>
);
})} */}
</div>
);
}
export default home;
产品.jsx
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
export const getProducts = createAsyncThunk("getProducts", async () => {
const response = await axios.get("https://api.escuelajs.co/api/v1/products");
return response;
});
const initialState = {
products: [],
};
export const productsSlice = createSlice({
name: "counter",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(getProducts.fulfilled, (state, action) => {
state.products = action.payload;
});
},
});
export const {} = productsSlice.actions;
export default productsSlice.reducer;
我实现了第二种解决问题的方法(你可以在 home.jsx 上看到),但我想使用
useSelector
钩子。
您未能将选择器函数传递给
useSelector
挂钩来实际选择已更新的产品状态。
const data = useSelector(); // <-- missing selector function!
假设您已按如下方式创建商店:
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import productsReducer from '../path/to/productsSlice';
// ... other imports ...
const rootReducer = combineReducers({
// ... other reducers
// matching slice name property, i.e. "counter", is a convention,
// but can be any valid Javascript identifier
counter: productsReducer,
});
const store = configureStore({
reducer: rootReducer,
});
那么您选择的产品“数据”就是
state.counter.products
。
const data = useSelector(state => state.counter.products);
不将所选值重命名为其他名称是很常见的,这可能会导致混乱。 示例:
const products = useSelector(state => state.counter.products);
或
const { products } = useSelector(state => state.counter);