类型错误:.map 不是函数

iLo*_*les 2 javascript reactjs react-hooks

我正在制作一个小的待办事项应用程序以了解有关 ReactJS 和 React Hooks 的更多信息。问题是我不明白我使用的list.map()有什么问题。它一直告诉我它不是一个函数。但是我一开始不明白我是如何将它用作函数的?

我一直在谷歌上查看我做错了什么。我尝试以多种方式更改我的代码,但我似乎无法弄清楚出了什么问题。一旦我单击“提交”按钮,它就会崩溃并给出TypeError: list.map is not a function错误消息。

function ToDoList() {
  const [list, setlist] = useState(["Test 1", "Test 2"]);
  const [newItem, setnewItem] = useState("");

  const handleChange = e => {
    setnewItem(e.target.value);
    console.log(newItem);
  };

  const handleSubmit = () => {
    setlist(...list, newItem);
  };

  return (
    <div>
      <input onChange={handleChange} />
      <button onClick={handleSubmit}>Submit</button>
      <ul>
        {list.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <AppTitle />
      <ToDoList />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试添加newItem到list并通过 .map() 呈现列表。当我启动应用程序时,“测试 1”和“测试 2”渲染,但添加到列表并重新渲染它会使其崩溃。

Dac*_*nny 7

此运行时错误的原因handleSubmit()是将list状态更新为非数组类型:

  const handleSubmit = () => {
    /* 
    The list is spread into the arguments of setlist() meaning that state
    is updated to the first value of the list array
    */ 
    setlist(...list, newItem);
  };
Run Code Online (Sandbox Code Playgroud)

handleSubmit()因此,当被调用时,list状态值不再是一个数组,这反过来意味着list.map()不再定义,因此出现错误:

“.map() 不是函数”。

如果您更改组件中的以下代码部分,这将确保将list其更新为新数组(其中“newItem”的值附加到该新数组的末尾):

  const handleSubmit = () => {

    /* 
    Update the list state to a new array, with newItem appended to the
    end of it. This ensures the list state remains as an array type,
    ensuring the list.map() is defined 
    */
    setlist([...list, newItem]);
  };
Run Code Online (Sandbox Code Playgroud)

  • @iLoveSpicyNoodles 不客气!祝您的项目一切顺利:) (2认同)