菜单打开时,React-select 根据国家列表冻结

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

我正在使用 React Select,并且有一个 API,我可以在其中获取国家/地区列表。 API中有256个国家代码。用户必须选择国家/地区。但是当菜单打开时屏幕冻结。原因是标志图像。我用

react-world-flag
。并下载所有图像。

我想如果我使用

useTransition
钩子,我就可以解决我的问题。但我不确定。如果您有解决方案,请回答这个问题。

我的代码

import axios from "axios";
import React from "react";
import { useTransition, useEffect, useState } from "react";
import Select from "react-select";
import Flag from "react-world-flags";

const ReactSelectFlag = () => {
  const [countries, setCountries] = useState([]);
  const [isPending, startTransition] = useTransition();
  const [menuIsOpen, setMenuIsOpen] = useState(false);

  useEffect(() => {
    axiosInstance.get("v1/countries").then(res => {
      setCountries(res.data.data);
    });
  }, []);

  const handleGet = () => {
    startTransition(() => setMenuIsOpen(true));
  };

  return (
    <Select
      options={countries}
      getOptionValue={option => option?.id}
      menuIsOpen={menuIsOpen}
      onMenuOpen={handleGet}
      onMenuClose={() => setMenuIsOpen(false)}
      getOptionLabel={option => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <span style={{ marginRight: "6px" }}>
            <Flag code={option?.code} width="24px" height="14px" />
          </span>{" "}
          {option?.code} - {option?.name}{" "}
        </div>
      )}
    />
  );
};

export default ReactSelectFlag;

此代码有效,但当我单击按钮时,下拉列表不会出现。渲染成功后,选项打开。我希望当我单击按钮时,必须打开选项,并且渲染后必须显示所有标志。

javascript reactjs react-hooks react-select usetransition
1个回答
0
投票
import axios from "axios";
import React, { useEffect, useState } from "react";
import Select from "react-select";
import { FixedSizeList as List } from "react-window";
import Flag from "react-world-flags";

const ReactSelectFlag = () => {
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    axios.get("v1/countries").then((res) => {
      setCountries(res.data.data);
    });
  }, []);

  const VirtualizedMenu = ({ children, maxHeight, getValue }) => {
    const [value] = getValue();
    const initialOffset = countries.indexOf(value) * 35;

    return (
      <List
        height={maxHeight || 200} // Set a default value for maxHeight
        itemCount={children.length}
        itemSize={35}
        initialScrollOffset={initialOffset}
      >
        {({ index, style }) => <div style={style}>{children[index]}</div>}
      </List>
    );
  };

  return (
    <Select
      options={countries}
      getOptionValue={(option) => option?.id}
      components={{ Menu: (props) => <VirtualizedMenu {...props} /> }}
      getOptionLabel={(option) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <span style={{ marginRight: "6px" }}>
            <Flag code={option?.code} width="24px" height="14px" />
          </span>{" "}
          {option?.code} - {option?.name}{" "}
        </div>
      )}
    />
  );
};

export default ReactSelectFlag;
© www.soinside.com 2019 - 2024. All rights reserved.