React / Typescript:对象作为React子对象无效

时间:2020-06-09 16:46:08

标签: reactjs typescript react-hooks

这是我在控制台中遇到的错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {text, complete}). If you meant to render a collection of children, use an array instead.

这是我的下面的代码:

import React, { Fragment, useState } from "react";
import ReactDOM from "react-dom";

type FormElement = React.FormEvent<HTMLFormElement>;

interface ITodo {
  text: string;
  complete: boolean;
}

export default function App(): JSX.Element {
  const [value, setValue] = useState<string>("");
  const [todos, setTodos] = useState<ITodo[]>([]);

  const addTodo = (text: string) => {
    const newTodos: ITodo[] = [...todos, { text, complete: false }];
    setTodos(newTodos);
  };

  const handleSubmit = (e: FormElement): void => {
    e.preventDefault();
    addTodo(value);
    setValue("");
  };

  return (
    <Fragment>
      <h1>Todo List</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          required
        />
        <button type="submit">Add Todo</button>
      </form>
      <div>
        {todos.map((todo: ITodo, index: number) => (
          <div key={index}>{todo}</div>
        ))}
      </div>
    </Fragment>
  );
}

const root = document.getElementById("app-root");
ReactDOM.render(<App />, root);

起初我以为我的地图有问题,但后来看不到任何问题。知道我在代码中错过了什么吗? 这是一个非常简单的待办事项列表应用程序,目前该功能正在添加待办事项并将其显示在输入下方的屏幕上。

1 个答案:

答案 0 :(得分:1)

您可能想更改

<div key={index}>{todo}</div>

<div key={index}>{todo.text}</div><div key={index}>{todo.complete}</div>

todos.map函数内部

,因为todo是无法自然地由React渲染的对象。