首页 > 解决方案 > 不能使用 this.state,因为我使用 eslint,“必须使用解构状态分配”/destructuring-assignment 反应

问题描述

我遇到了一些错误,因为我使用了一些 this.setState 语句,因此我无法调用我的语句。

我在这里遇到错误this.state.show

handleClick() {
    this.setState({ show: !this.state.show });   <<<------EROR HERE
  }

这是我的完整代码

    class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { show: false };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ show: !this.state.show });
  }

  render() {
    return (
      <HeroStyles>
        <Zoom>
          <div className="container">
            <div className="Kotak">
              <h1 className="heading">
                <span> this is hello </span>
                <h2>
                  stay{' '}
                  <span>
                    <Typewriter
                      loop={0}
                      cursor
                      cursorStyle="_"
                      delaySpeed={3000}
                      words={['Positive', 'Negative']}
                    />
                  </span>{' '}
                  <span>
                    <Typewriter
                      loop={1}
                      cursor
                      cursorStyle="_"
                      delaySpeed={3000}
                      words={['Kawan']}
                    />
                  </span>
                </h2>
              </h1>
              <Zoom delay={500}>
                <div className="foto">
                  waymo
                  <div className="lingkaran" />
                  <img src={foto} alt="" onClick={this.handleClick} />
                  Guna Dharma
                </div>
              </Zoom>
              <Zoom opposite when={this.state.show}>
                <h1>React Reveal</h1>
              </Zoom>
            </div>
          </div>
        </Zoom>
      </HeroStyles>
    );
  }
}

导出默认你好;

标签: javascriptreactjs

解决方案


eslint 规则destructuring-assignment是强制执行此操作的。

但是你有比这更大的问题,因为你不应该this.state在 a 期间阅读setState(),如果你想确保你会得到正确的值(因为React 组件状态可能是异步设置的。)

而是传递一个函数,将(当前)状态作为其参数:

  handleClick() {
    this.setState(state => { 
        return {show: !state.show } // not this.state.show
    });
  }

推荐阅读