【问题标题】:Use-State hook passing props down to child使用状态挂钩将道具向下传递给孩子
【发布时间】:2021-07-27 06:04:55
【问题描述】:

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

这是我收到的错误消息:

我想我可能在传递shoppingListsetShoppingList() 时输入/界面错误。

Here is a codesandbox reproduction.

【问题讨论】:

  • 如果我错了,请纠正我,但我的理解是 shoppingList 应该包含一个字符串数组?
  • @KiprasT 是的,这是正确的

标签: reactjs typescript use-state


【解决方案1】:

你可以看看React.useState()返回什么类型。

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

如您所见,setter 的类型为 Dispatch&lt;SetStateAction&lt;S&gt;&gt;

如果你往下走,你会看到

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

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

现在让我们看看SetStateAction&lt;A&gt;

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

它要么是一个简单的值,要么是一个接收前一个状态并返回一个新状态的函数。

那么如何修复你的类型呢?

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

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

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

【讨论】:

    【解决方案2】:

    编辑:我的回答非常具体。 @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}
    />
    

    【讨论】:

    • 谢谢!这行得通,我有一种预感,我需要拆分我的类型,因为它们似乎相互冲突。
    • 为了将来参考,您应该阅读@hendra 的答案,它提供的信息要多得多。
    • 是的,我做到了,我很感激@hendra 花时间向我解释:D
    猜你喜欢
    • 2018-08-25
    • 2017-06-03
    • 2017-08-22
    • 1970-01-01
    • 2018-12-25
    • 2020-08-08
    • 1970-01-01
    • 2018-04-09
    • 2016-03-19
    相关资源
    最近更新 更多