嗨,我正在使用 react.js/typescript 撰寫簡單的待辦事項應用程式。我一直在反復呼叫待辦事項
我可以在 1) 和 3) 呼叫 todo 但我不能呼叫 2)。
有什么不同。也許我的介面型別不好todo.type.tsx?
<TodoListItem todo={todos[0]} />{todos.map(todo=> { <TodoListItem todo={todo} /> })}{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: '[email protected]'
},
{
text: "todo2",
email2: '[email protected]'
}
])
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>
)
}
源代碼/模型/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>
);
};
uj5u.com熱心網友回復:
問題是它根本沒有回傳。
嘗試
<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
uj5u.com熱心網友回復:
你犯了一個括號錯誤。對于 JS/TS 中的任何函式,()表示回傳(您甚至不必使用關鍵字return),而{}表示只是運行該函式
在您的index.tsx檔案中:
import { TodoListItem } from '../components/todo';
export default function IndexPage(){
const [todos, setTods] = useState<Todo[]>([
{
text: 'todo1',
email2: '[email protected]'
},
{
text: "todo2",
email2: '[email protected]'
}
])
return (
<Layout>
<TodoListItem todo={todos[0]} /> // ★I can call (★1)
//Here, inside the map function you have used "{}" instead of "()" so the map function is simply iterating and not returning anything.
<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>
)
}
對此的修復可能是
<ul>
{todos.map((todo: Todo) => (
<TodoListItem todo={todo} />
))}
</ul>
或者
<ul>
{todos.map(todo=> {
return <TodoListItem todo={todo} />
})}
</ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349981.html
標籤:javascript 反应 打字稿
下一篇:為什么函式多載不提示錯誤?
