【问题标题】:TypeError: .map is not a function类型错误:.map 不是函数
【发布时间】:2019-12-18 14:43:31
【问题描述】:

我正在制作一个小型 To-Do 应用程序来了解有关 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>
  );
}

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

【问题讨论】:

  • 如果list.map不是一个函数,那么list不是一个列表。
  • 哦,所以它基本上告诉我我用我的 handleSubmit 函数打破了列表?这解释了 Dacre Denny 的回答。

标签: javascript reactjs react-hooks


【解决方案1】:

此运行时错误的原因是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);
  };

因此,当调用 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]);
  };

【讨论】:

  • 哇,非常感谢!那解决了它! :) 我永远不会猜到这一点。有没有理由让它给我那个特定的错误呢?为什么它告诉我它不是函数?
  • @iLoveSpicyNoodles 不客气 - 刚刚更新了答案。这有帮助吗? :)
  • 是的,这完全回答了我的问题! :) 非常感谢你的帮助和教我我做错了什么:)
  • @iLoveSpicyNoodles 不客气!祝你的项目一切顺利:)
猜你喜欢
  • 2022-11-19
  • 2021-03-29
  • 2016-02-26
  • 2013-04-01
  • 2016-03-06
  • 2017-08-16
  • 2020-02-28
  • 1970-01-01
相关资源
最近更新 更多