如何正确传递道具以更改JSON文件中的密钥?

时间:2019-12-11 23:48:18

标签: javascript reactjs react-hooks react-props

我正在尝试创建一个函数,该函数将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">&#128946;</i>
  );

  return (
    <>
      <li
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
        onClick={() => toggleFavorite(props.id)}
      >
        {props.name}
      </li>
      {isSelected}
    </>
  );
};

export default Band;

0 个答案:

没有答案