【问题标题】:React: Add item in the beginning of list反应:在列表的开头添加项目
【发布时间】:2021-04-15 17:44:21
【问题描述】:

我有一个显示姓名的简单列表。当我尝试添加新名称时,它会添加到列表末尾。

如何在列表顶部添加新名称? 我试过push()unshift(),每次都出现以下错误

list.map is not a function

代码: https://codesandbox.io/s/gallant-minsky-0xgmg?file=/src/App.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

export default () => {
  const initialList = [
    {
      id: "1",
      name: "John"
    },
    {
      id: "2",
      name: "Doe"
    },
    {
      id: "3",
      name: "Seb"
    }
  ];

  const [list, setList] = React.useState(initialList);
  const [name, setName] = React.useState("");

  function handleChange(event) {
    setName(event.target.value);
  }

  function handleAdd() {
    const newList = list.concat({ name });
    setList(newList);
    setName("");
  }

  return (
    <div>
      <div>
        <input type="text" value={name} onChange={handleChange} />
        <button type="button" onClick={handleAdd}>
          Add
        </button>{" "}
      </div>

      <ul>
        <div>
          {list.map((item, index) => (
            <li key={item.id}>
              <div>{item.name}</div>
            </li>
          ))}
        </div>
      </ul>
    </div>
  );
};

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    当你通过 array.push(element) 或 array.unshift(element) 向数组添加元素时,它总是会返回数组的新长度。

        const initialList = [
            {
              id: "1",
              name: "John"
            },
            {
              id: "2",
              name: "Doe"
            },
            {
              id: "3",
              name: "Seb"
            }
          ];
      const [list, setList] = React.useState(initialList);
      const [name, setName] = React.useState("");
    
        
        
    
    function handleAdd() {
          const newList = list.push({ name }); // returns new length
          setList(newList);
          setName("");
     }
    

    在这里它将 newList 的值设置为 4,而不是 new List

    <div>
      {list.map((item, index) => (
          <li key={item.id}>
            <div>{item.name}</div>
          </li>
          ))}
    </div>
    

    当您尝试在数字 4 上应用 ma​​p 时,它将返回 .map is not function,因为它仅适用于不在数字上的项目列表。与 unshift 相同。

    【讨论】:

    • 我明白了。我使用了上面的建议并且它有效。所以在这种情况下根本不能使用 push 和 unshift 吧?
    • @AlyaKra 如果你使用 push 它将在现有列表的末尾推送它不会返回新列表。如果您使用相同的列表来设置状态,那么 react 认为没有任何变化,因为即使在设置状态之后它也具有相同的引用,因此它不会重新渲染。
    • 啊,我明白了。非常感谢!
    【解决方案2】:

    您可以使用扩展运算符并拥有:

    function handleAdd() {
        const newList = [{ name }, ...list];
        setList(newList);
        setName("");
    }
    

    【讨论】:

      【解决方案3】:

      import React, { useState } from "react";
      import ReactDOM from "react-dom";
      import "./styles.css";
      
      export default () => {
        const initialList = [
          {
            id: "1",
            name: "John"
          },
          {
            id: "2",
            name: "Doe"
          },
          {
            id: "3",
            name: "Seb"
          }
        ];
      
        const [list, setList] = React.useState(initialList);
        const [name, setName] = React.useState("");
      
        function handleChange(event) {
          setName(event.target.value);
        }
      
        function handleAdd() {
          const newList = [{ name }, ...list]; // simply create a new array and spread the previous one
          setList(newList);
          setName("");
        }
      
        return (
          <div>
            <div>
              <input type="text" value={name} onChange={handleChange} />
              <button type="button" onClick={handleAdd}>
                Add
              </button>{" "}
            </div>
      
            <ul>
              <div>
                {list.map((item, index) => (
                  <li key={item.id}>
                    <div>{item.name}</div>
                  </li>
                ))}
              </div>
            </ul>
          </div>
        );
      };

      【讨论】:

        猜你喜欢
        • 2014-12-29
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        相关资源
        最近更新 更多