Trying to toggle state but getting a TypeError: drawer.setState is not a function

Trying to toggle state but getting a TypeError: drawer.setState is not a function

我有一组抽屉项目,我正在尝试切换它们的状态。我写了一个函数,我认为它可以用于切换各个抽屉项目,但它不起作用。我收到 TypeError: drawer.setState is not a function。不确定如何让它工作。有没有人对如何做到这一点有任何提示?提前致谢!

class CategoryList extends React.Component<CategoryListProps, CategoryListState> {
  constructor(props) {
    super(props);
    const drawers = this.props.items.map((item) => ({
      open: false,
      heading: item.heading,
      drawerHeading: item.drawerHeading,
      drawerContent: item.drawerContent,
    }));
    this.state = { drawers };
    this.handleToggle = this.handleToggle.bind(this);
  }

  handleToggle = (drawer) => {
    drawer.setState({ open: !drawer.open });
  };

  render() {
    return (
      <div className="pb-10">
        <h5 className="pb-8 text-white md:text-center">{this.props.heading}</h5>
        <div className="">
          {this.state.drawers.map((drawer) => (
            <div className="flex flex-col items-baseline w-full py-6 text-white border-b md:flex-row border-b-white">
              <h3 className="flex-shrink-0">{drawer.heading}</h3>
              <div className="right">
                <p className="font-serif text-xl">{drawer.drawerHeading}</p>
                {drawer.open && <CategoryListDrawer drawer={drawer} />}
              </div>
              <div className={`flex items-center self-end justify-center w-12 h-12 ml-auto transform border border-white rounded-full toggle-btn cursor-pointer ${drawer.open === true ? 'open' : ''}`} onClick={this.handleToggle(drawer)}>
                <span className="w-6 h-6 overflow-hidden transition-transform duration-75 transform toggle"></span>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

drawer 是一个看起来像这样的对象:

{
  open: false,
  heading: item.heading,
  drawerHeading: item.drawerHeading,
  drawerContent: item.drawerContent,
}

它没有 setState 功能。要设置状态,您需要执行 this.setState。但是您还需要以其他一些方式修改您的代码以使其工作。

首先,您将更新整个数组,因此您的代码需要找到数组中的项目并仅更新该项目。你传递一个索引而不是抽屉可能更容易,但我们可以让它与 drawer:

一起工作
handleToggle = (drawer) {
  this.setState(prev => {
    const index = prev.drawers.indexOf(drawer);
    const newDrawers = [...prev.drawers];
    newDrawers[index] = {
      ...newDrawers[index],
      open: !newDrawers[index].open
    }
    return { drawers: newDrawers }
  });
}

其次,您当前在渲染期间立即调用 handleToggle,然后将未定义传递给 onClick。相反,您需要创建一个新函数并将其传递给 onClick。即,而不是这个:

onClick={this.handleToggle(drawer)}

这样做:

onClick={() => this.handleToggle(drawer)}

第三,绑定箭头函数没有用,可以删掉这一行:

this.handleToggle = this.handleToggle.bind(this);