【问题标题】:can't using this.state because i use eslint, "Must use destructuring state assignment" /destructuring-assignment react不能使用 this.state,因为我使用 eslint,“必须使用解构状态分配”/destructuring-assignment 反应
【发布时间】:2021-07-16 05:03:25
【问题描述】:

我遇到了一些错误,因为我使用了一些 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>
    );
  }
}

导出默认Hello;

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您有 destructuring-assignment 规则。

强制使用 props、状态和上下文的解构赋值(react/destructuring-assignment)

你必须先从状态中解构你想要的东西:

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

如果您不想这样做,可以从 ESLint 中禁用该规则。

【讨论】:

    【解决方案2】:

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

    但是你有比这更大的问题,因为你不应该在setState() 期间阅读this.state,如果你想确保你会得到正确的值(因为React component state may be set asynchronously。)

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2019-03-09
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2019-11-27
      • 2019-02-04
      • 1970-01-01
      • 2020-03-16
      相关资源
      最近更新 更多