MUI 自动完成更改不会更新值



我正在从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>Post Categories:</h3>
<SelectPostsCatsOptions
selectedCategories={selectedCategories}
setSelectedCategories={setSelectedCategories}
onChange={(event, newSelectedCategories) =>
setSelectedCategories(newSelectedCategories)
}
value={selectedCategories}
/>
<p>Selected Categories:</p>
</div>
</form> 
</div>
</>  
</div>
);
}

SelectPostsCatsOptions:

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="Categories" />
)}
value={value}
onChange={onChange}
/>
</div>
);
}

我不知道我在这里错过了什么,为什么我不能从自动完成添加或删除一个标签!

更新您的useEffect深度数组。https://legacy.reactjs.org/docs/hooks-effect.html[]表示只调用mount

每次渲染

都会被调用

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

相关内容

  • 没有找到相关文章

最新更新