在onChange事件中更新zustand存储创建输入延迟

问题描述 投票:0回答:1

当我尝试在 onChange 事件中设置 zustand 变量的状态时,遇到输入延迟问题。

const BuildOrder = (props: { setOpen: Function }) => {
  const { almacenes, isLoadingAlmacenes } = useGetAlmacenes();
  const { articlesRes, isLoadingArticles } = useGetArticlesBySearch();
  const {
    warehouseSelected,
    setWarehouseSelected,
    setArticles,
    articles,
    setArticlesFetched,
    articlesFetched,
    setSearch,
  } = useDirectlyPurchaseRequestOrderStore(
    (state) => ({
      warehouseSelected: state.warehouseSelected,
      setWarehouseSelected: state.setWarehouseSelected,
      setArticles: state.setArticles,
      articles: state.articles,
      setArticlesFetched: state.setArticlesFetched,
      articlesFetched: state.articlesFetched,
      setSearch: state.setSearch,
    }),
    shallow
  );
  const [articleSelected, setArticleSelected] = useState<Article | null>(null);
  const [amountText, setAmountText] = useState('');
  const [warehouseError, setWarehouseError] = useState(false);
  const [articleError, setArticleError] = useState(false);`your text`
  const [amountError, setAmountError] = useState(false);

  if (isLoadingAlmacenes)
    return (
      <Box sx={{ display: 'flex', flex: 1, justifyContent: 'center', p: 6 }}>
        <CircularProgress size={40} />
      </Box>
    );
  return (
    <Stack sx={{ display: 'flex', flex: 1, mt: 2 }}>
      <Stack sx={{ display: 'flex', flex: 1, maxWidth: 300 }}>
        <Typography sx={{ fontWeight: 500, fontSize: 14 }}>Seleccionar almacén</Typography>

        <TextField
          select
          label="Almacén"
          size="small"
          error={warehouseError}
          helperText={warehouseError && 'Selecciona un almacén'}
          value={warehouseSelected}
          onChange={(e) => {
            setWarehouseError(false);
            setWarehouseSelected(e.target.value);
          }}
        >
          {almacenes.map((warehouse) => (
            <MenuItem key={warehouse.id} value={warehouse.id}>
              {warehouse.nombre}
            </MenuItem>
          ))}
        </TextField>
      </Stack>
      <Divider sx={{ my: 2 }} />
      <Box
        sx={{
          display: 'flex',
          flex: 1,
          justifyContent: 'space-between',
          columnGap: 2,
          flexDirection: { xs: 'column', sm: 'row' },
          rowGap: { xs: 2, sm: 0 },
        }}
      >
        <Stack sx={{ display: 'flex', flex: 1 }}>
          <Typography sx={{ fontWeight: 500, fontSize: 14 }}>Seleccionar articulo</Typography>
          <Autocomplete
            disablePortal
            fullWidth
            filterOptions={filterArticleOptions}
            onChange={(e, val) => {
              e.stopPropagation();
              setArticleSelected(val);
              setArticleError(false);
            }}
            loading={isLoadingArticles && articlesFetched.length === 0}
            getOptionLabel={(option) => option.nombre}
            options={articlesFetched}
            value={articleSelected}
            noOptionsText="No se encontraron artículos"
            renderInput={(params) => (
              <TextField
                {...params}
                error={articleError}
                helperText={articleError && 'Selecciona un articulo'}
                placeholder="Artículos"
                sx={{ width: '50%' }}
                onChange={(e) => {
                  setSearch(e.target.value);
                }}
              />
            )}
          />
        </Stack>

在这个自动完成中,我动态渲染我的文章,我渲染一个输入 TextField 来控制搜索状态来渲染一些项目,当我在 TextField 中写入时,这会更新 onChange 事件中的值存储,但这会在 textField 上创建输入延迟,看起来很迟钝。


export const useGetArticlesBySearch = () => {
  const [isLoadingArticles, setIsLoadingArticles] = useState(true);
  const [articlesRes, setArticles] = useState<Article[]>([]);
  const search = useDirectlyPurchaseRequestOrderStore(useShallow((state) => state.search));

  useEffect(() => {
    const fetchData = async () => {
      setIsLoadingArticles(true);
      try {
        const res = await getArticlesBySearch(search);
        setArticles(res);
      } catch (error) {
        console.log(error);
      } finally {
        setIsLoadingArticles(false);
      }
    };
    fetchData();
  }, [search]);
  return { isLoadingArticles, articlesRes };
};

我在这里将我的商店的状态值称为搜索文章。

我解决了为自定义钩子创建 useState 和 prop 的问题,但我想知道,是否还有另一种方法可以仅使用 zustand 来完成?

我试图知道是否有一种方法可以声明 zustand 存储变量并避免文本字段上的输入延迟。

reactjs typescript state zustand
1个回答
0
投票

我见过一些例子,他们不会破坏同一行中的所有状态,而是将每行的每个项目分开:

const { warehouseSelected } = useDirectlyPurchaseRequestOrderStore((state) => ({ warehouseSelected: state.warehouseSelected })
const { setWarehouseSelected} = useDirectlyPurchaseRequestOrderStore((state) => ({ setWarehouseSelected: state.setWarehouseSelected}) 
...rest of the items

我会尝试一下,看看它是否可以提高性能

© www.soinside.com 2019 - 2024. All rights reserved.