Привязка многодетной строки зависания или сбоя веб-страницы с помощью React с помощью инструментария redux

#reactjs #typescript #redux #redux-toolkit #react-typescript

Вопрос:

https://codesandbox.io/s/large-data-array-with-redux-toolkit-forked-7tp63?file=/demo.tsx

В приведенном примере codesandbox я использую react typescript с redux-инструментарием

в примере codesandbox. Я пытаюсь связать страны с помощью флажка и текстового поля. Когда я устанавливаю флажки, это выглядит медленно, и редактирование текстового поля также кажется очень медленным. некоторое время он ломает страницу.

Я не уверен, что делаю что-то не так.

Ответ №1:

Вы должны сделать CountryItem своим собственным компонентом и сделать его чистым компонентом:

 import React, { FC, useEffect } from "react";
import { createStyles, Theme, makeStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import { countryList } from "./dummyData";
import { Checkbox, Grid, TextField } from "@material-ui/core";
import { useAppDispatch, useAppSelector } from "./store/hooks";
import {
  setCountries,
  setCountrySelected,
  setCountryValue
} from "./store/slice/geography-slice";
import { Country } from "./interface/country.modal";

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      width: "100%",
      backgroundColor: theme.palette.background.paper
    }
  })
);
const CountryItem: FC<{ country: Country }> = ({ country }) => {
  console.log('render item',country.name)
  const dispatch = useAppDispatch();
  const handleCheckboxChange = (
    event: React.ChangeEvent<HTMLInputElement>,
    country: Country
  ) => {
    const selectedCountry = { ...country, isSelected: event.target.checked };
    dispatch(setCountrySelected(selectedCountry));
  };

  const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedCountry = { ...country, value: event.target.value };
    dispatch(setCountryValue(selectedCountry));
  };

  return (
    <ListItem button>
      <Checkbox
        checked={country?.isSelected ?? false}
        onChange={(event) => {
          handleCheckboxChange(event, country);
        }}
      />
      <ListItemText primary={country.name} />
      <TextField value={country?.value ?? ""} onChange={handleTextChange} />
    </ListItem>
  );
};
const PureCountryItem = React.memo(CountryItem)
export default function SimpleList() {
  const classes = useStyles();
  const dispatch = useAppDispatch();
  const { countries } = useAppSelector((state) => state.geography);

  useEffect(() => {
    dispatch(setCountries(countryList));
  }, []);

  return (
    <div className={classes.root}>
      <Grid container>
        <Grid item xs={6}>
          <List component="nav" aria-label="secondary mailbox folders">
            {countries.map((country, index) => (
              <PureCountryItem country={country} key={`CountryItem__${index}`} />
            ))}
          </List>
        </Grid>
      </Grid>
    </div>
  );
}