Use-State 钩子传递道具 child

Use-State hook passing props down to child

大家好,我是打字稿的新手。我无法将 usestate() 道具传递给我的 child 元素。

这是我收到的错误消息:

我想我传递 shoppingListsetShoppingList() 的 typing/interface 可能是错误的。

Here is a codesandbox reproduction.

你可以看看是什么类型React.useState() returns.

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

如您所见,setter 的类型为 Dispatch<SetStateAction<S>>

如果你再往下看,你会看到

type Dispatch<A> = (value: A) => void;

所以你的 setter 必须是一个函数类型,它接收一个参数并且 returns void。

现在让我们来看看SetStateAction<A>

type SetStateAction<S> = S | ((prevState: S) => S);

它可以是一个简单的值,也可以是一个接收前一个状态和 returns 一个新状态的函数。

那么如何修正你的类型?

const Recipe = (props: {
  recipe: Irecipe;
  shoppingList: string[];
  setShoppingList: Dispatch<SetStateAction<string[]>>;
}) => {...}

或者,如果您不打算使用 prevState 功能,您可以简化类型:

const Recipe = (props: {
  recipe: Irecipe;
  shoppingList: string[];
  setShoppingList: (value: string[]) => void;
}) => {...}

编辑:我的回答非常具体。 @hendra 的回答更完整,值得信赖。

在types.ts中:

export type shoppingList = string[];
export type setShoppingList = React.Dispatch<React.SetStateAction<string[]>>;

在Recipe.tsx中:

import { Irecipe, shoppingList, setShoppingList } from "../types";

const Recipe = (props: {
  recipe: Irecipe;
  shoppingList: shoppingList;
  setShoppingList: setShoppingList;
}) => {...

在App.tsx中:

import { Irecipe, shoppingList as shoppingListType } from "./types";
...
const [shoppingList, setShoppingList] = useState<shoppingListType>([]);
...
<Recipe
  key={recipe.recipe.url}
  recipe={recipe}
  shoppingList={shoppingList}
  setShoppingList={setShoppingList}
/>