reactjs - React Typescript 对象可能是“未定义的”。TS2532
问题描述
当我为一个简单的待办事项项目映射一组对象时,我试图弄清楚为什么会出现此错误。我是 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"
/>
解决方案
list.map
仅当 list 是一个数组时才有效,如果 list 未定义或为 null,则会抛出错误。创建状态时const [list, setList] = useState();
,您不提供任何初始值,因此list
未定义。如果您的 asyncuseEffect
在第一次渲染之前无法完成,您的应用程序将崩溃,因为list
isundefined
并且您在.map
没有任何检查的情况下调用。
你有这样的选择:
- 为列表提供起始值,例如空列表:
const [list, setList] = useState([]);
- 在定义列表之前不允许组件渲染,所以提前返回:
if (list == null) {
return <></>;
}
推荐阅读
- angular - 调用取消订阅后,茉莉花不会继续执行订阅回调中的代码
- azure - 带有 Javascript 运行时的 Azure 函数读取 httptrigger 请求很慢
- java - 从 JButton 菜单(java)中单击 JLabel 时不显示图像
- random-forest - h2o DRF 看不见的分类值处理
- c++ - 在 C++11 中没有开销的别名模板最佳替代方案的专业化
- facebook-messenger-bot - 通用模板和列表模板不起作用
- kubernetes - Kubernetes 集群中运行的 Pod 需要什么目标端口
- json - JSON文件解析问题
- java - 使用代理时无法连接到 Maven 存储库
- c# - 使用反射查找通用方法时发现模棱两可的匹配