【问题标题】:Destructuring props assignment解构道具分配
【发布时间】:2019-02-03 22:23:07
【问题描述】:

我在使用 eslint 时遇到了一些问题。它要求我使用解构道具分配,但是当我更改代码时,它会中断。

有什么想法吗?

这是完整的代码

class LoginPage extends React.Component {
  submit = data =>

    // This is how I tried to fix it!
    // {
    //   const { login, history } = this.props;
    //   login(data).then(() => history.push('/'));
    // };

    // This is what I have, its working but eslint is complaining.
    this.props.login(data).then(() => this.props.history.push('/'));

  render() {
    return (
        <div>
            <h1>Login Page</h1>
            <LoginForm submit={this.submit} />
        </div>
    );
  }
}

LoginPage.propTypes = {
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }).isRequired,
  login: PropTypes.func.isRequired /* eslint-disable-line */
};

export default connect(
  null,
  { login }
)(LoginPage);

修改后的代码出现的错误是:

TypeError: Object(...)(...).then is not a function 
LoginPage._this.submit
src/ components/pages/LoginPage.js:10

7 | class LoginPage extends React.Component {
8 |     submit = data => {
9 |         const { login, history } = this.props;
10 |        login(data).then(() => history.push('/'));
11 |    };
12 | 
13 |    render() {

它说问题在第 10 行。

任何帮助将不胜感激!

【问题讨论】:

    标签: reactjs destructuring


    【解决方案1】:

    当函数中有多个表达式时,需要将其写在{} 中。在你的情况下,你会写

    submit = data => {
    
        const { login, history } = this.props;
        login(data).then(() => history.push('/'));
    
    }
    

    【讨论】:

    • 是的,对不起,我忘了把它添加到代码中。我一开始在我的解决方案中使用了花括号。
    【解决方案2】:

    您的修复看起来不错,您是否尝试将submit = (data) =&gt; { ... } 放在花括号中?除非您使用的是 coffeescript 之类的东西,否则多个语句(一个解构赋值然后调用)需要在一个块中。这可能是 eslint 抱怨的原因,但它的工作原理并非如此——它只是一种表达方式,所以不需要阻塞。

    【讨论】:

      【解决方案3】:

      正如另一点指出的那样,您需要花括号{}。像下面这样:

      submit = data => {
      
          const { login, history } = this.props;
          login(data).then(() => history.push('/'));
      
      }
      

      es6 箭头函数遵循以下规则:

      • 如果函数后面有一个表达式在同一行,它将返回它。
      • 一个参数可以省略括号
      • 当您编写多行代码时,您需要添加 {} 并使用 return 语句显式返回它。

      【讨论】:

        猜你喜欢
        • 2020-03-16
        • 2019-05-11
        • 2019-04-20
        • 2021-11-17
        • 1970-01-01
        • 2018-08-11
        • 1970-01-01
        • 2021-03-23
        相关资源
        最近更新 更多