gpt4 book ai didi

reactjs - 如何将 react-hooks、redux 和 typescript 结合在一起?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:25 25 4
gpt4 key购买 nike

我一直在尝试结合 React-hooks、Redux 和 Typescript。每次我修复一个错误时,都会出现一个新错误。

谁能看出问题是什么?

现在我收到关于我的 reducer 的以下错误:

Unhandled Rejection (TypeError): action.places is not iterable

没有 typescript ,这段代码可以工作。所以我应该遗漏了一些东西或者在类型方面做错了什么。

// 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};它基本上遍历原始对象的键并将原始对象的键/值对复制到新的对象文字中。

From MDN

对于函数调用:myFunction(...iterableObject);

对于数组文字或字符串:[...iterableObject, 'one', '2', 'three'];

对于对象文字(ECMAScript 2018 中的新功能):let objectClone = { ...object } ;

所以在 reducer ,返回应该是一个对象。如果你想要一个数组,你可以在创建对象之后创建它

const placeReducer = (state = initialState, action: PlaceActionTypes) => {
switch (action.type) {
case FETCH_DATA:
return {...state, ...action.places};

default:
return state;
}
};

关于reactjs - 如何将 react-hooks、redux 和 typescript 结合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com