搜尋

首頁  >  問答  >  主體

"如何使MUI Autocomplete的onChange事件能夠更新值"

我正在從API中獲取自動完成選項,它完美地獲取到了,並且還顯示了從API返回的已選擇選項,但我面臨的問題是,無論我嘗試刪除還是添加一個值(類別),它都不會刪除或新增。

線上示範Codesandbox

PostInfo.jsx:

import SelectPostsCatsOptions from "../../components/autocomplete/SelectPostsCatsOptions";
import postInfo from "./postInfo.json";
export default function PostInfo() {
  const [categories, setCategories] = useState([]);
  const [selectedCategories, setSelectedCategories] = useState([]);

  useEffect(() => {
    const getPost = async () => {
      try {
        setCategories(postInfo[0].categories);
        setSelectedCategories(postInfo[0].categories);
      } catch (err) {}
    };
    getPost();
  });

  return (
   
    <div className="PostInfoPage">
      <>
        <div>
          <form>
            <div>
              <h3>帖子类别:</h3>
              <SelectPostsCatsOptions
                selectedCategories={selectedCategories}
                setSelectedCategories={setSelectedCategories}
                onChange={(event, newSelectedCategories) =>
                  setSelectedCategories(newSelectedCategories)
                }
                value={selectedCategories}
              />
              <p>已选择的类别:</p>
            </div>
          </form> 
        </div>
      </>  
    </div>
  );
}

選擇PostsCatsOptions:

import categories from "./postsCategories.json";

export default function SelectPostsCatsOptions({
  selectedCategories,
  setSelectedCategories,
  onChange,
  value
}) {
  return (
    <div>
      <Autocomplete
        id="categories"
        disablePortal
        multiple
        getOptionLabel={(category) => category.catName}
        options={categories}
        disableGutters
        isOptionEqualToValue={(option, value) =>
          option.catName === value.catName
        }
        renderOption={(props, categories) => (
          <li {...props} key={categories.id}>
            {categories.catName}
          </li>
        )}
        renderTags={(value, getTagProps) =>
          value.map((option, index) => (
            <Chip
              key={option.id}
              label={option.catName}
              {...getTagProps({ index })}
            />
          ))
        }
        renderInput={(params) => (
          <TextField {...params} placeholder="类别" />
        )}
        value={value}
        onChange={onChange}
      />
    </div>
  );
}

我不知道我在這裡漏掉了什麼,為什麼我不能從自動完成中新增或刪除一個標籤!

P粉649990273P粉649990273443 天前730

全部回覆(1)我來回復

  • P粉512526720

    P粉5125267202023-09-16 14:02:30

    更新你的useEffect依賴陣列。 https://legacy.reactjs.org/docs/hooks-effect.html []意味著只在掛載時呼叫

    它在每次渲染時都會被呼叫

      useEffect(() => {
        const getPost = async () => {
          try {
            setCategories(postInfo[0].categories);
            setSelectedCategories(postInfo[0].categories);
          } catch (err) {}
        };
        getPost();
      }, []); //<--- 改变
    

    回覆
    0
  • 取消回覆