使用useState构建一个带有Reaction(Vite)的待办应用程序.在try 实现本地存储时,我遇到了一个错误,我的应用程序在npm run dev
服务器上运行得很好,但在实时提交时,表单功能被 destruct ,并抛出一个TypeError:
index-b568087f.js:61 Uncaught TypeError: t is not iterable
at o (index-b568087f.js:61:377)
at onClick (index-b568087f.js:61:798)
at Object.Ld (index-b568087f.js:37:9855)
at Ad (index-b568087f.js:37:10009)
at Id (index-b568087f.js:37:10066)
at Ds (index-b568087f.js:37:31459)
at Rc (index-b568087f.js:37:31876)
at index-b568087f.js:37:36788
at tc (index-b568087f.js:37:8967)
at Yo (index-b568087f.js:37:33162)
这对我来说是第一次,所以任何帮助都是感激的.下面是我的App.jsx,其中包含我的应用程序的所有代码.
import "./App.css";
// components
import Header from "./Components/Header.jsx";
import { useState, useEffect } from "react";
function App() {
const localList = JSON.parse(localStorage.getItem("list"));
// state with list of todos
const [list, setList] = useState(localList);
useEffect(() => {
localStorage.setItem("list", JSON.stringify(list));
}, [list]);
// state with input value
const [input, setInput] = useState("");
// function to add todos
const addTodo = (todo) => {
const newTodo = {
id: Math.random(),
todo: todo,
};
// add the todo to the list
if (input !== "" && input !== " ") {
setList([...list, newTodo]);
}
// clear input box
setInput("");
};
const submitOnEnter = (e) => {
e.preventDefault();
if (e.key === "Enter") {
if (input === "" || input === " ") {
return;
}
document.getElementById("addTask").click();
}
};
const deleteTodo = (id) => {
// filter out todo with id
const newList = list.filter((todo) => todo.id !== id);
// set list state to be the filtered list
setList(newList);
};
return (
<>
<div className="container">
<Header />
<div className="inputContainer">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
id="inputField"
onKeyUp={submitOnEnter}
/>
<button id="addTask" onClick={() => addTodo(input)}>
Add
</button>
</div>
<ul>
{list?.map((todo) => (
<div className="todoItemContainer">
<li className="todoItem" key={todo.id}>
{todo.todo}
</li>
<button
className="deleteTodo"
onClick={() => deleteTodo(todo.id)}
>
×
</button>
</div>
))}
</ul>
</div>
</>
);
}
export default App;
最初,我试图解决.map读取未定义的内容的问题.我通过添加三进制运算符(list?.map)
来判断list
是否为数组,从而修复了这个问题.
在那之后,npm run dev
服务器上的一切都继续正常工作,但活动提交的功能随后崩溃了.
我已经查看了DevTool,我非常确定错误来自调用AddTodo()函数,但我对如何解决它感到困惑.我已经判断了其他一些Stack Overflow帖子,但在弄清楚这一点上遇到了一些困难.
当然,我不能预览开发服务器,但我已经在下面链接了活动提交.