我正在从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粉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(); }, []); //<--- 改变