React Typescript 对象可能是“未定义的”。 TS2532

时间:2021-01-26 16:58:23

标签: reactjs typescript undefined

当我为一个简单的 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"
                  />

2 个答案:

答案 0 :(得分:3)

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

你有这样的选择:

  1. 为列表提供起始值,例如空列表:const [list, setList] = useState([]);
  2. 在定义列表之前不允许组​​件渲染,所以提前返回:
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 接口的数组。