简体   繁体   中英

Reactjs: how to keep a selected item state in the pagination? React-hooks

I would like to keep the coloring of the selected item in the state, however, when changing pages (Ex: from 1 to 2 and back to 1), it loses the coloring and as default states start as false, a request is sent to remove all items from the state in useEffect.

is filtering 10 items per page, and when I change pages, apparently the state resets and starts from scratch, even though there are selected items on the page.

Types

type ISkySelected = {
    id: string
}

interface ISkusProps {
    id: string
    description: string
    code_sap: string
    stock_pe: string
    stock_atc: string

    enableSku: boolean
    skusSelectedList: (selected: ISkySelected) => void
    removeSkuSelected: (selected: ISkySelected) => void
}
export function CardList ({ id, description, code_sap, stock_pe, stock_atc, enableSku, skusSelectedList, removeSkuSelected }: ISkusProps) {
  const [selected, setSelected] = useState<boolean>(false)
  const [color, setColor] = useState<string>('red.500')
  const [cursor, setCursor] = useState<string>('')

  function selectedSku (event: MouseEvent) {
    event.preventDefault()

    if (!enableSku) {
      return
    }

    setSelected(!selected)
  }

  useEffect(() => {
    if (selected) {
      setColor('red.500')
      skusSelectedList({ id: id })
    }

    if (!selected) {
      removeSkuSelected({ id: id })
      setColor('white')
    }
  }, [selected])

  useEffect(() => {
    if (enableSku) {
      setCursor('pointer')
    }

    if (!enableSku) {
      setSelected(false)
      setCursor('')
    }
  }, [enableSku])

   return (
    <Box
        cursor={cursor}
        borderRadius='2px'
        overflow='hidden'
        h='400px'
        w='225px'
        mt={5}
        borderWidth='4px'
        borderColor={color}
        onClick={(e) => selectedSku(e)}
    > ...myComponente </Box>
  )
})

PRINTS

selected an item: enter image description here

back one page: enter image description here

returning to the page that was: enter image description here

The problem is that when CardList is unmounted and remounted, the state of the component is reinitialized. You can store IDs array of selected cards higher up the tree. And then pass the selected prop to the card. For example like this:

interface CardProps {
  id: string;
  selected: boolean;
  toggleSelect: (id: string) => void;
}

const Card = ({ id, selected, toggleSelect }: CardProps) => {
  const [color, setColor] = useState<string>('red.500');

  const handleClick = () => {
    toggleSelect(id);
    setColor(selected ? 'red.500' : 'white');
  };

  return (
    <Box onClick={handleClick} color={color}>
      ...Component
    </Box>
  );
};

const List = () => {
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const toggleCardSelected = (cardId: string) => {
    const isSelected = selectedIds.includes(cardId);
    if (isSelected) {
      setSelectedIds((prev) => prev.filter((id) => id !== cardId));
    } else {
      setSelectedIds((prev) => [...prev, cardId]);
    }
  };

  return (
    <>
      {cards.map(({ id }) => (
        <Card id={id} selected={selectedIds.includes(id)} toggleSelect={toggleCardSelected} />
      ))}
    </>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM