首页 > 解决方案 > 在反应的打字稿中简单重复调用数组在类似 3 例的 1 例中不起作用

问题描述

您好,我正在使用 react.js/typescript 编写简单的待办事项应用程序。我坚持反复调用 todos

我可以在 1) 和 3) 打电话给 todo,但我不能打电话给 2)

有什么不同。也许我的界面类型不好todo.type.tsx

  1. <TodoListItem todo={todos[0]} />
  2. {todos.map(todo=> { <TodoListItem todo={todo} /> })}
  3. {todos.map(todo => (<li>{todo.text} - {todo.email2}</li> ))}

还是我的 Props2 调用todo.tsx不好?

React.FC<Props2> = ({ todo })

这是显示

==== ( localhost:9000 rendering shows this ) ======
text1"[shown in TodoListItem]"contato@gabrielrufino.com
text1 - contato@gabrielrufino.com
text2 - darthvader@starwars.com

src/pages/index.tsx


    import { TodoListItem } from '../components/todo';

    export default function IndexPage(){
    
      const [todos, setTods] = useState<Todo[]>([
          {
            text: 'todo1',
            email2: 'contato@gabrielrufino.com'
          },
          {
            text: "todo2",
            email2: 'darthvader@starwars.com'
          }
        ])
    
      return (
          <Layout>
            <TodoListItem todo={todos[0]} />   // ★I can call   (★1)
            <ul>
              {todos.map(todo=> {
                 <TodoListItem todo={todo} />  //  ★I CANT call (★2)
              })}
            </ul>
            <ul>
            {todos.map(todo => (
              <li>{todo.text} - {todo.email2}</li> // ★I can call   (★3)
            ))}
           </ul>
          </Layout>
        )
    }

src/model/todo.type.tsx


    interface Todo {
        text: string;
        email2: string;
      }

      interface Props2 {
        todo: Todo;
      }

src/components/todo.tsx

import React, { FC } from 'react';


export const TodoListItem: React.FC<Props2> = ({ todo }) => {
    return (
      <li>
         {todo.text} 
           <br> "shown in TodoListItem"
           </br>
         {todo.email2}
      </li>
    );
  };

标签: javascriptreactjstypescript

解决方案


问题是它根本没有返回。

尝试

      <ul>
        {todos.map((todo: Todo) => (
          <TodoListItem todo={todo} />
        ))}
      </ul>

或者

       <ul>
          {todos.map(todo=> {
             return <TodoListItem todo={todo} /> 
           })}
       </ul>

代替

        <ul>
          {todos.map(todo=> {
             <TodoListItem todo={todo} />  //  ★I CANT call (★2)
           })}
        </ul>

代码沙箱 => https://codesandbox.io/s/nervous-bartik-vl8hs


推荐阅读