我正在使用react-hooks管理JSX.Elements列表。但是,一旦元素更改,尝试将其删除将导致意外行为。

我曾尝试使用useReducer,按索引删除等,但仍发生意外的更新结果。

FolderPage.tsx

import React, { useState, useEffect } from 'react';
import { Button, Box, Grid } from 'grommet';
import { Add, Close } from 'grommet-icons';

import { Files } from '../Component/Files/Files';
import { ePub } from '../extension/ePub/ePub';

interface Props {}

export const FolderPage: React.FC<Props> = () => {
  const [state, setState] = useState([<Files openFileHandlers={[ePub]} />]);

  const newFolderPanel = () => setState(prev => prev.concat(<Files openFileHandlers={[ePub]} />));

  const removePanel = (panel: JSX.Element) => setState(prevState => prevState.filter(s => s !== panel));

  return (
    <div>
      <Box align="start" pad="xsmall">
        <Button icon={<Add />} label="New Folder Panel" onClick={newFolderPanel} primary />
      </Box>
      {state.map((s, index) => (
        <Grid key={index}>
          <Box align="end">
            <Button
              icon={<Close color="white" style={{ backgroundColor: 'red', borderRadius: '50%', padding: '.25rem' }} />}
              type="button"
              onClick={() => removePanel(s)}
            />
          </Box>
          {s}
        </Grid>
      ))}
    </div>
  );
};


例如,在用法中:
reactjs - 如何正确管理JSX.Elements列表的 react 状态-LMLPHP

我应该更改我的代码,以便我的删除单击将删除匹配的元素?

最佳答案

有一种解决方法。对于数组中的每个项目。与其直接存储项目,不如将其存储为{id:yourAssignedNumber,content:item}。

这样,您可以控制ID,并仅通过比较ID即可将其删除。这样,它将正常工作。

import React, { useState, useRef } from 'react';
import { Button, Row, Col } from 'antd';

import { Files } from '../Components/Files/Files';
import { fileHandler } from '../model/fileHandler';

interface Props {
  fileHandlers?: fileHandler[];
}

export const FolderPage: React.FC<Props> = ({ fileHandlers }) => {
  const [state, setState] = useState([{ key: -1, content: <Files fileHandlers={fileHandlers} /> }]);
  const key = useRef(0);

  const newFolderPanel = () =>
    setState(prev =>
      prev.concat({
        key: key.current++,
        content: <Files fileHandlers={fileHandlers} />
      })
    );

  const removePanel = (key: number) => setState(prevState => prevState.filter(s => s.key !== key));

  return (
    <Row>
      <Button type="primary" icon="plus" onClick={newFolderPanel} style={{ margin: '.75rem' }}>
        New Foldr Panel
      </Button>
      {state.map(({ key, content }) => (
        <Col key={key}>
          <div
            style={{
              background: '#75ff8133',
              display: 'grid',
              justifyItems: 'end',
              padding: '.5rem 1rem'
            }}>
            <Button onClick={() => removePanel(key)} icon="close" type="danger" shape="circle" />
          </div>
          {content}
        </Col>
      ))}
    </Row>
  );
};

关于reactjs - 如何正确管理JSX.Elements列表的 react 状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58422709/

10-14 00:10