简体   繁体   English

React typescript 如何在 tsx 中使用类型 useState 和渲染列表

[英]React typescript how use types useState and render list in tsx

How can I set type to useState and render list with map in React TypeScript?如何在 React TypeScript 中将类型设置为useState并使用 map 渲染列表?

I have a component:我有一个组件:

export type Item = {
  name: string;
  title: string;
};
export type ItemTypes = {
  item: Item[];
};

export const ItemList: FC = () => {
   const [items, setItems] = useState<ItemsTypes | []>([])

   useEffect(() => {
    let items = [
      {
        name: "A",
        title: "B",
      },
      {
        name: "C",
        title: "D",
      }
    ]
    setItems()
   }, [);

   return (
     <div>
         {items?.map((item) => (
          <>{item.name}</>
         ))}
     </div>
   )
}

And under .map line red stroke and saying:并在.map线红色笔划下并说:

any
Property 'map' does not exist on type 'ItemTypes | []'. 

Where is my mistake?我的错误在哪里?

As defined ItemTypes is not an array but instead an object having property item, hence the error.正如定义的ItemTypes不是一个数组,而是一个具有属性 item 的 object,因此出现错误。 Use Item[] instead.请改用Item[]

const [items, setItems] = useState<Item[]>([])

There are a couple of things wrong with the your implementation.您的实施存在一些问题。

First if you want to export the type alias ItemTypes you can set the type alias for ItemTypes like this export type ItemTypes = Item[] .首先,如果要export类型别名ItemTypes ,可以为ItemTypes设置类型别名,例如export type ItemTypes = Item[]

Second, you are never calling setItems with the items you have created in useEffect .其次,您永远不会使用您在useEffect中创建的items调用setItems

Lastly, because you are trying to access the name property on each item you should be checking item.length in a conditional otherwise it will throw an error cannot access property name of undefined if you do try to load the items asynchronously.最后,因为您尝试访问每个项目的name属性,所以您应该在条件中检查item.length ,否则如果您尝试异步加载项目,它将抛出错误cannot access property name of undefined

Solution解决方案


    export type Item = {
      name: string;
      title: string;
    };

    export type ItemTypes = Item[];

    export const ItemList: FC = () => {
       const [items, setItems] = useState<ItemsTypes | []>([])

       useEffect(() => {
        let items = [
          {
            name: "A",
            title: "B",
          },
          {
            name: "C",
            title: "D",
          }
        ]
        setItems(items)
       }, []);

       return (
         <div>
             {
               items.length && items.map((item) => (<p>{item.name}</p>) )

             }
         </div>
       )
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 tsx 组件名称循环对象列表(JSON 文件)并在 React tsx(TypeScript)中渲染它 渲染 JSON 中引用的 react-icons,如何? - Loop over List of Objects (JSON file) with tsx component name and render it in React tsx (TypeScript) Render react-icons referenced in JSON, how? 如何在React + TypeScript中使用react-datetime(在tsx内部) - How to use react-datetime with react + typescript (inside tsx) 如何在 typescript 的 React 中正确使用 useState 钩子? - How to use useState hook in React with typescript correctly? 如何在使用TypeScript(TSX)编写的React应用程序中使用Facebook Relay? - How to use Facebook Relay in a React app written in TypeScript (TSX)? React tsx 渲染间隔更改列表 - React tsx Render Intervally changing list 使用 TypeScript 在 useState React Hook 上设置类型 - Set types on useState React Hook with TypeScript 如何在TSX中呈现由字符串确定的React组件 - How to render react component determined by string in TSX 如何使用 useState 和 React-redux-firebase 重新渲染 - How to use useState with React-redux-firebase to re-render 如何使用 usestate 和 setstate 而不是 this.setState 使用 react 和 typescript? - How to use usestate and setstate instead of this.setState using react and typescript? 如何将 TypeScript generics 与 React 渲染道具一起使用 - How to use TypeScript generics with React render props
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM