奇怪的班级成员

时间:2018-06-21 15:55:45

标签: javascript

在运行示例中,我对类定义的“状态”和“登录”成员感到困惑:

class Login extends React.Component {
    state = {
        redirectToReferrer: false
    };

    login = () => {
        fakeAuth.authenticate(() => {
            this.setState({ redirectToReferrer: true });
        });
    };

    render() {
        const { from } = this.props.location.state
            || { from: { pathname: "/" } };
        const { redirectToReferrer } = this.state;

        if (redirectToReferrer) {
            return <Redirect to={from} />;
        }

        return (
            <div>
                <p>You must log in to view the page at {from.pathname}</p>
                <button onClick={this.login}>Log in</button>
            </div>
        );
    }
}

对于“登录”,我想确认这是Login类的函数成员,对吗?我可以理解使用箭头函数的动机是绑定“ this”的问题,但是我没有在ES6书中看到这种语法。看起来像{}的顶层,它只是定义了一个分配有箭头功能的变量。

对于“状态”,这看起来很简单,但是我知道它必须定义“登录”的成员,因为有一个“ this.state”引用。但是我不理解语法,我的ES6书说必须在类的构造函数中定义任何实例属性。这种定义还有其他特殊含义吗?

1 个答案:

答案 0 :(得分:1)

在React中定义初始状态的标准方法如下:

class Login extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            redirectToReferrer: false
        };
    }

    ....

}

但是,有一些像 unstated 这样的库,可以让您定义如下状态:

// BookContainer.js
import { Container } from 'unstated'
class BookContainer extends Container {
  state = {
    books: [],
    booksVisible: false
  }
  addBook = book => {
    const books = [...this.state.books, book]
    this.setState({ books })
  }
  toggleVisibility = () => {
    this.setState({
      booksVisible: !this.state.booksVisible
    })
  }
}
export {
  BookContainer
}

编辑:正如您已经说过的那样,关于登录方法是关于绑定this

此:

login = () => {
        fakeAuth.authenticate(() => {
            this.setState({ redirectToReferrer: true });
        });
    };

与执行此操作相同:

class Login extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            redirectToReferrer: false
        };
        this.login = this.login.bind(this); // Bind the this
    }

    login(){
        fakeAuth.authenticate(() => {
            this.setState({ redirectToReferrer: true }); // This is not undefined
        });
    }

}

您可以在unstated官方页面上找到更多信息