在 React-Select (MultiSelect) 状态变化时删除 "Select Box" 中的项目

Delete Item in "Select Box" on State Change in React-Select (MultiSelect)

我想在我的状态更新时删除 Select 框 中的项目。 在我当前的实施中,项目已从选项列表下拉列表中删除,但 Select 框 仍显示已删除的值。

设置

当前行为

即使在删除项目后它仍然显示在 Select 框中

目标

更新 Select 框以及状态更改。

这是SandBox

提前致谢:)

您还需要将更新后的选项同步到 Select 组件:

您将需要使用新状态并相应地更新它们。

于是变成了:

import "./styles.css";
import { useState } from "react";
import Select from "react-select";
import { Button } from "@material-ui/core";

export default function App() {
  const [items, setItems] = useState([
    { id: 1, text: "Text 1" },
    { id: 2, text: "Text 2" },
    { id: 3, text: "Text 3" }
  ]);

  const [options, setOptions] = useState([]);

  const deleteItem = (getID) => {
    setItems(items.filter((single) => single.id !== getID));
    setOptions(options.filter((single) => single.id !== getID));
  };

  return (
    <div className="App">
      <div style={{ marginTop: 40, marginBottom: 40 }}>
        {items.map((data) => (
          <li>
            {data.text}
            <Button
              onClick={() => deleteItem(data.id)}
              color="primary"
              style={{ marginLeft: 20 }}
            >
              Delete
            </Button>
          </li>
        ))}
      </div>

      <Select
        isMulti
        isSearchable
        maxMenuHeight={200}
        isClearable={false}
        options={items}
        getOptionLabel={(option) => option.text}
        getOptionValue={(option) => option.text}
        value={options}
        onChange={(options) => setOptions(options)}
      />
    </div>
  );
}