React Typescript 对象可能是 'undefined'。 TS2532

React Typescript Object is possibly 'undefined'. 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 是未定义的。如果您的异步 useEffect 在第一次渲染之前无法完成,您的应用程序将会崩溃,因为 listundefined 并且您在没有任何检查的情况下调用 .map

你有这样的选择:

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

您需要为您的 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 接口的数组。