我正在尝试创建一个函数,该函数将JSON文件中的值从false翻转为true,反之亦然。这是JSON文件,其中包含以下四个文件:
[
{
"id": "0",
"name": "Led Zeppelin",
"isFavorite": false
},
[...]
这是用来显示每个频段的组件:
const Options = () => {
const bandElements = bandList.map(band => (
<Band
key={band.id}
id={band.id}
isFavorite={band.isFavorite}
name={band.name}
/>
));
return (
<div>
<ul>{bandElements}</ul>
</div>
);
};
export default Options;
最后,我尝试在其中切换isFavorite属性的组件:
const Band = props => {
const [hovered, setHovered] = useState(false);
const [allBands, setAllBands] = useState(bandList);
function toggleFavorite(id) {
const newArr = allBands.map(band => {
if (band.id === id) {
return { ...band, isFavorite: !band.isFavorite };
}
return band;
});
setAllBands(newArr);
}
const isSelected = props.isFavorite ? (
<h3>OK</h3>
) : (
hovered && <i className="icon-fix">🞲</i>
);
return (
<>
<li
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onClick={() => toggleFavorite(props.id)}
>
{props.name}
</li>
{isSelected}
</>
);
};
export default Band;