代码之家  ›  专栏  ›  技术社区  ›  dragi

分解道具分配

  •  1
  • dragi  · 技术社区  · 6 年前

    我在react中遇到了一些与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() {
    

    任何帮助都将不胜感激!

    3 回复  |  直到 6 年前
        1
  •  2
  •   Shubham Khatri    6 年前

    当一个函数中有多个表达式时,需要在 {}

    submit = data => {
    
        const { login, history } = this.props;
        login(data).then(() => history.push('/'));
    
    }
    
        2
  •  1
  •   timotgl    6 年前

    你的修复看起来不错,你试过 submit = (data) => { ... } 戴着大括号?除非您使用类似coffeescript的东西,否则多个语句(一个解构赋值,然后调用)需要在一个块中。这可能就是eslint抱怨的原因,但它的工作方式不同——它只是一个表达式,所以不需要阻塞。

        3
  •  1
  •   Willem van der Veen    6 年前

    另一个指出你需要大括号 {} . 如下所示:

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

    es6

    • 如果函数后面的同一行有一个表达式,它将返回它。
    • 对于一个参数,可以使用括号
    • 当你写多行的时候,你需要加上 return 声明。