反应挂钩从数组中删除项目

时间:2020-07-01 10:38:00

标签: reactjs react-hooks

在我的react hooks组件中,我正在从对象数组中渲染数据。

const lineInfo = [
  {
    id: '001',
    line: 's-1125026',
    arrival: '7:30',
    departure: '8:00',
    authorization: 'User 1',

  },
  {
    id: '002',
    line: 's-1125027',
    arrival: '8:01',
    departure: '8:50',
    authorization: 'User 1',
  },

.map()中,我使用以下数据返回数据:

       <div>
         {lineInfo.map((line) => (
              <Row key={`line_${line.id}`}>

 // remaining code removed for length

列表返回正常,所以现在我试图从列表中删除一行。 删除功能

  const [list, setList] = useState(lineInfo);

  function handleRemove(id) {
    console.log('id' id);
    const newList = list.filter((line) => line.id !== id);
    setList(newList);
  }

删除按钮

        <Button
          className={style.close_button}
          onClick={() => handleRemove(line.id)}
         >
           <img src={close} alt="trash" />
        </Button>
</Row>

我遇到的问题是在控制台日志中,是仅从数组中删除了line.id而不是整个数据行。

  1. 如何删除属于特定ID的所有数据?
  2. 即使控制台日志显示已删除文本,为什么我的行中显示的文本也没有从视图中删除?

我对钩子不太熟悉,只能找到有关类组件的特定问题的示例。预先感谢。

2 个答案:

答案 0 :(得分:2)

您应该显示带有挂钩的已定义状态。在这种情况下,list而不是lineInfo

 <div>
   {list.map((line) => (
     <Row key={`line_${line.id}`}>

 // remaining code removed for length

答案 1 :(得分:1)

您不应渲染lineInfo,而应从本地状态渲染列表:

const { useState, useCallback } = React;
const lineInfo = [
  {
    id: '001',
    line: 's-1125026',
    arrival: '7:30',
    departure: '8:00',
    authorization: 'User 1',
  },
  {
    id: '002',
    line: 's-1125027',
    arrival: '8:01',
    departure: '8:50',
    authorization: 'User 1',
  },
];
//make row pure component using React.memo
const Row = React.memo(function Row({ item, remove }) {
  return (
    <div>
      <pre>{JSON.stringify(item, undefined, 2)}</pre>
      <button onClick={() => remove(item.id)}>
        remove
      </button>
    </div>
  );
});

const App = () => {
  const [list, setList] = useState(lineInfo);
  //make remove a callback that is only created
  //  on App mount using useCallback with no dependencies
  const remove = useCallback(
    (removeId) =>
      //pass callback to setList so list is not a dependency
      //  of this callback
      setList((list) =>
        list.filter(({ id }) => id !== removeId)
      ),
    []
  );

  return (
    <ul>
      {list.map((line) => (
        <Row
          key={`line_${line.id}`}
          item={line}
          remove={remove}
        />
      ))}
    </ul>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>