【问题标题】:How to update the previous properties of state after onClick event?onClick 事件后如何更新之前的 state 属性?
【发布时间】:2021-11-28 14:36:14
【问题描述】:

所以我想用对象数组更新我的状态的先前属性。最初我只制作了两个对象。我想在我的 moviedb 应用程序中实现书签功能。当我点击图标时,它应该改变颜色以及在我的useState 中更改isFavorited 属性的值。

const [isActive, setActive] = useState({
        favorited: false,
        customColor: "white"
    });


const handleToggle = () => {
    setActive({ ...isActive, !favorited});
    if(isActive.favorited){
        setActive( {...isActive, customColor: "red"});
    }else{
        setActive( {...isActive, customColor: "white"});
    }
}

我在单击图标时调用handleToggle 函数。如何制作它以便每次使用useState 单击它时切换收藏夹的值?我在!favorited 上收到错误曲线

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    {...isActive, !favorited} 不是有效的 JS 语法。

    尝试将函数重写为:

    const handleToggle = () => {
      setActive((prevState) => {
        return {
          ...prevState,
          favorited: !prevState.favorited,
          customColor: prevState.favorited ? "red" : "white",
        };
      });
    };
    

    【讨论】:

    • 虽然它解决了我的问题,但如何在<BsFillBookmarkFill className="bookmark" size={34} onClick={handleToggle} color={this.isActive.customColor} /> 中设置customColor
    • 请提供一个单独的问题并提供上下文。
    【解决方案2】:

    您应该使用 prevState 更新状态:-

     setActive((prevState) => ({
           ...prevState, favorited : !favorited}
        ));
    

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      相关资源
      最近更新 更多