当我为一个简单的 todo 项目映射对象数组时,我试图弄清楚为什么会出现此错误。 我是 Typescript 的新手,我不知道为什么会发生这种情况,为什么我的状态“列表”作为数组很好地记录在控制台中。 你能检查一下出了什么问题吗?
const ToDoListItem = () => {
const [list, setList] = useState();
useEffect(() => {
fetch("http://localhost:1337/lists", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((data) => setList(data));
}, []);
const findData = async () => {
fetch("http://localhost:1337/lists", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((data) => setList(data));
};
console.log(list);
return (
<Container>
<Row>
{list.map((e, i) => { //where the issue is coming from
console.log(todo);
return (
<Col xs="12" style={{ display: "flex", justifyContent: "center" }}>
<div className="todo-container">
<InputGroup
style={{
display: "flex",
alignItems: "center",
width: "100%",
justifyContent: "space-evenly",
}}
>
<Input
className="input-text"
value={e.todo}
placeholder="to do"
/>
<Input
type="checkbox"
checked={e.iscompleted}
className="check-box"
/>
答案 0 :(得分:3)
list.map
仅在 list 是数组时有效,如果 list 未定义或为空,则会抛出错误。当您创建状态 const [list, setList] = useState();
时,您不提供任何初始值,因此 list
未定义。如果您的异步 useEffect
在第一次渲染之前没有成功,您的应用程序将会崩溃,因为 list
是 undefined
并且您在没有任何检查的情况下调用 .map
。
你有这样的选择:
const [list, setList] = useState([]);
if (list == null) {
return <></>;
}
答案 1 :(得分:1)
您需要为 useState 列表值添加一个类型,例如并基于您的代码:
interface ListItem {
todo: string
isCompleted: boolean
}
const ToDoListItem = () => {
// Set the initial value to an empty array
const [list, setList] = useState<ListItem[]>([]);
// Rest of your code
{list.map((e, i) => {
// More code
}}
}
这样你就可以输入你的状态,所以它可以让打字稿来推断对象值
请注意,useState 之前的 <ListItem[]>
告诉您该值应该是 ListItem 接口的数组。