reactjs - 如何将 react-hooks、redux 和 typescript 结合在一起?
问题描述
我一直在尝试结合 React-hooks、Redux 和 Typescript。每次我修复错误时,都会出现一个新错误。
谁能看到问题似乎是什么?
现在我收到关于我的减速器的以下错误:
未处理的拒绝(TypeError):action.places 不可迭代
没有打字稿,这段代码就可以工作。所以我应该在类型方面遗漏一些东西或做错事。
// Types
export interface Place {
type: string;
geometry: Geometry;
properties: Properties;
id: number;
}
interface Geometry {
type: string;
coordinates: [number, number];
}
interface Properties {
Id: string;
Title: string;
Url: string;
ImageUrl: string;
Bullets: boolean;
}
export const FETCH_DATA: string = "FETCH_DATA";
export interface FetchDataAction {
type: typeof FETCH_DATA;
places: Place[];
}
export type PlaceActionTypes = FetchDataAction;
export type AppActions = PlaceActionTypes;
// Action
// places = axios.create({baseURL}) (the API is an array of type Place[])
export const fetchPlaces = () => async (dispatch: Dispatch) => {
const response = await places.get(`places`);
dispatch({
type: "FETCH_DATA",
payload: response.data
});
};
// Reducer
export const initialState: Place[] = [];
const placeReducer = (state = initialState, action: PlaceActionTypes) => {
switch (action.type) {
case FETCH_DATA:
return [...state, ...action.places];
default:
return state;
}
};
// Here is my Component
const HomePage = () => {
const places: Place[] = useSelector((state: any) => state.places);
const dispatch = useDispatch();
useEffect(() => {
places.length === 0 && dispatch(fetchPlaces());
});
console.log(places);
return <div>HomePage</div>;
};
解决方案
使用扩展运算符时出现错误。
在您的代码中,您尝试使用用于可迭代对象的语法来传播对象。对象传播的正确语法const cloneObject = {...originalObject};
本质上是迭代原始对象的键并将原始的键/值对复制到新的对象字面量中。
对于函数调用:myFunction(...iterableObject);
对于数组文字或字符串:[...iterableObject, 'one', '2', 'three'];
对于对象文字(ECMAScript 2018 中的新功能)let objectClone = { ...object }
:
所以在 中reducer
,return 应该是一个对象。如果你想要一个数组,你可以在创建对象后创建它
const placeReducer = (state = initialState, action: PlaceActionTypes) => {
switch (action.type) {
case FETCH_DATA:
return {...state, ...action.places};
default:
return state;
}
};
推荐阅读
- arrays - 一个简单的哈希数组循环,即使它有效,我也会收到错误警告,这是为什么呢?
- vue.js - 如何使 v-col 内容可滚动?
- mongodb - 如何在查询中将两个字段的差异与常量进行比较?
- php - 在 shopify 管理仪表板面板中显示额外的自定义信息
- processing - 处理切断堆栈跟踪
- php - PHP 致命错误:无法声明类 Stripe\\Stripe,因为该名称已在使用中
- javascript - If statement not working properly even though everything is right
- jquery - 如何以编程方式侦听 jquery 触发的点击
- ios - overrideUserInterfaceStyle 可以覆盖系统警报/操作表吗?
- python-3.x - 有什么方法可以使用python通过api删除完整的电子表格