首页 > 解决方案 > 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"
                  />

标签: reactjstypescriptundefined

解决方案


list.map仅当 list 是一个数组时才有效,如果 list 未定义或为 null,则会抛出错误。创建状态时const [list, setList] = useState();,您不提供任何初始值,因此list未定义。如果您的 asyncuseEffect在第一次渲染之前无法完成,您的应用程序将崩溃,因为listisundefined并且您在.map没有任何检查的情况下调用。

你有这样的选择:

  1. 为列表提供起始值,例如空列表:const [list, setList] = useState([]);
  2. 在定义列表之前不允许组​​件渲染,所以提前返回:
if (list == null) {
  return <></>;
}

推荐阅读