reactjs React DOM在状态更改后未(正确)更新

5q4ezhmt  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(180)

这一个的行为让我感到困惑。通过点击“添加按钮”几次创建了一个列表。从列表中删除一个项目(通过点击项目旁边的“删除”)正确地从列表中删除项目(并更新状态),但显示显示最后一个项目被删除,而您选择删除的项目仍然存在。我没有正确更新状态吗:

import { useState } from "react"

export const App = () => {
    const [records, setRecords] = useState({ data: [], errState: false })

    const addRecord = () => {
        let newList = [...records.data]
        newList.push(`This Will Be Record ${newList.length}`)
        console.log(newList)
        setRecords(ps => ({ ...ps, data: newList }))
    }

    const delRecord = ({ target }) => {
        const id = parseInt(target.getAttribute("data-row"))
        let newList = [...records.data]
        newList.splice(id, 1)
        setRecords(ps => ({ ...ps, data: newList }))
    }

    const buildRows = () => {
        return records.data.map((r, rndx) => {
            return (
                <div style={{ display: "flex",marginBottom:"10px" }}>
                    <div style={{ flex: 1, paddingRight: "20px" }}><input id={`test-${rndx}`}/></div>
                    <div style={{ width: "50px" }}><button onClick={delRecord} data-row={rndx}>Delete</button></div>
                </div>

            )
        })
    }

    return (
        <div style={{ width: "800px", margin: "0 auto", textAlign: "center" }}>
            {buildRows()}
            <button onClick={addRecord}>Add Record</button>
        </div>
    )
}

字符串
CodeSandbox

egmofgnx

egmofgnx1#

考虑为每个不是从其数组索引派生的项目设置唯一的id。在渲染项目时使用此id值作为key prop,以确保React从DOM中删除适当的元素:

const { useState } = React;

const App = () => {
  const [records, setRecords] = useState({ data: [], errState: false });

  const addRecord = () => {
    let newList = [...records.data];
    newList.push({
      value: `This Will Be Record ${newList.length}`,
      id: Date.now(),
    });
    console.log(newList);
    setRecords((ps) => ({ ...ps, data: newList }));
  };

  const delRecord = ({ target }) => {
    const id = parseInt(target.getAttribute('data-row'));
    let newList = records.data.filter((item) => item.id !== id);
    setRecords((ps) => ({ ...ps, data: newList }));
  };

  const buildRows = () => {
    return records.data.map((r) => {
      return (
        <div style={{ display: 'flex', marginBottom: '10px' }} key={r.id}>
          <div style={{ flex: 1, paddingRight: '20px' }}>
            <input id={`test-${r.id}`} />
          </div>
          <div style={{ width: '50px' }}>
            <button onClick={delRecord} data-row={r.id}>
              Delete
            </button>
          </div>
        </div>
      );
    });
  };

  return (
    <div style={{ width: '800px', margin: '0 auto', textAlign: 'center' }}>
      {buildRows()}
      <button onClick={addRecord}>Add Record</button>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('app')).render(<App />);

个字符

相关问题