【发布时间】:2021-07-24 05:25:34
【问题描述】:
我想使用 typescript / react / redux_thunk 获取 api 数据并使用该数据制作一个简单的应用程序
这是我的代码:
type.tsx:
export interface Iproduct {
id: number;
title: string;
price: number;
description: string;
category: string;
image: string;
}
Actions.ts
import { Iproduct } from "../types/type";
export const getProduct = () => (dispatch: any) => {
axios
.get<Iproduct[]>("https://fakestoreapi.com/products")
.then((res) => dispatch({ type: "GET_PRODUCT", payload: res.data }))
.catch((err) => {
console.log(err);
});
};
减速机:
import { Iproduct } from "../types/type";
interface Iproducs {
products: any[];
}
const INITALIZE_STATE: Iproducs = {
products: [],
};
type Action = { type: string; payload: any[] };
export const reducer = (state = INITALIZE_STATE, action: Action) => {
switch (action.type) {
case "GET_PRODUCT":
return { ...state, products: action.payload };
default:
return state;
}
};
App.tsx:
const state = useSelector((state: Iproduct[]) => state);
const dispatch = useDispatch();
const [products, setproducts] = useState<Iproduct[]>([]);
useEffect(() => {
dispatch(getProduct());
}, []);
useEffect(() => {
setproducts(state);
products.forEach((e: Iproduct) => console.log(e));
});
我想在 app.tsx 文件中使用 useSelector 接收到的数据进行映射,但出现错误
“TypeError:products.map 不是函数”
如果你能告诉我我是在哪里做的,我会很高兴,因为我刚刚学会了打字稿,所以我无法解决这些错误。
注意:我在项目中使用redux-thunk
【问题讨论】:
-
我没有看到你在代码中的任何地方调用
products.map..? -
fwiw 从另一个状态派生的状态是一种反模式。在这里,您正在从 redux 状态创建一个反应状态,这不好。
标签: reactjs typescript redux redux-thunk tsx