首页 > 解决方案 > 如何将 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>;
};

标签: reactjstypescriptreduxreact-reduxreact-hooks

解决方案


使用扩展运算符时出现错误。

在您的代码中,您尝试使用用于可迭代对象的语法来传播对象。对象传播的正确语法const cloneObject = {...originalObject};本质上是迭代原始对象的键并将原始的键/值对复制到新的对象字面量中。

来自 MDN

对于函数调用: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;
  }
};

推荐阅读