我正在從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 (<>); }>
選擇PostsCatsOptions:
import categories from "./postsCategories.json"; export default function SelectPostsCatsOptions({ selectedCategories, setSelectedCategories, onChange, value }) { return (); }category.catName} options={categories} disableGutters isOptionEqualToValue={(option, value) => option.catName === value.catName } renderOption={(props, categories) => ( {categories.catName} )} renderTags={(value, getTagProps) => value.map((option, index) => ()) } renderInput={(params) => ( )} value={value} onChange={onChange} />
我不知道我在這裡漏掉了什麼,為什麼我不能從自動完成中新增或刪除一個標籤!
更新你的
useEffect
依賴陣列。https://legacy.reactjs.org/docs/hooks-effect.html[]
意味著只在掛載時呼叫它在每次渲染時都會被呼叫