反应:"toISOString is not a function"

React: "toISOString is not a function"

我正在用 Next.js 编写待办事项列表。我想实现一个 dueDate 函数,如果我发出 post 请求,我会得到这个错误:

Unhandled Runtime Error
TypeError: dueDate.toISOString is not a function

我不知道如何解决这个问题,如果有人能帮助我就太好了:)

我的代码:

const [newTodo, setNewTodo] = useState<any>({
    title: "",
    description: "",
})
const [dueDate, setDueDate] = useState<Date>(new Date())
const addTodo = () => {
    axios.post("http://localhost:5000/todos", {
        title: newTodo.title,
        description: newTodo.description,
        dueDate: dueDate.toISOString().slice(0, 10)
    }).then(res => {
        setTodos([...todos, res.data])
        setNewTodo({
            title: "",
            description: "",
            dueDate: "",
        })
    })
}

    
<input className="dueDate" type="date" onChange={(e) => setDueDate(e.target.value)} />

问题是 input 调用 setDueDate 传递的 e.target.valuestring 而不是 Date,你知道:

The "toISOString is not a function" error occurs when the toISOString() method is called on a value that is not a date object.

要解决这个问题,只需修改输入的 onChange:

<input className="dueDate" type="date" onChange={(e) => setDueDate(new Date(e.target.value))} />

For more info