"如何使MUI Autocomplete的onChange事件能夠更新值"
P粉649990273
P粉649990273 2023-09-15 17:21:34
0
1
710

我正在從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粉649990273
P粉649990273

全部回覆(1)
P粉512526720

更新你的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();
  }, []); //<--- 改变
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!