这在React类函数中为null

Zac*_*iro 0 javascript ecmascript-6 reactjs react-redux

我重构了一个从ES5到ES6的React类,现在当我点击一个调用按钮时,行开头this.state.dispatch(logIn(this.state.logIn))的初始this值为null.超级怪异.

这是我的班级:

class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
            panelIsOpen: false,
            registration: {},
            login: {},
        };
    }

    signUp() {
        this.props.dispatch(signUp(this.state.registration));

        this.setState({
            registration: {},
        });
    }

    logIn() {
        debugger; // this is `null here`
        this.props.dispatch(logIn(this.state.login));

        this.setState({
            login: {},
        });
    }

    togglePanel(e) {
        this.setState({ panelIsOpen: !this.state.panelIsOpen} );
    }

    render() {
        const {elements} = this.props;
        const {registration, login} = this.state;

        return (
            // some stuff 
        );
    }
};

Home.propTypes = {
    elements: React.PropTypes.array,
    dispatch: React.PropTypes.func,
    user: React.PropTypes.object,
};

const mapStateToProps = ({elements, auth}) => {
    return {
        elements: getElementsByKeyName(elements, 'visibleElements'),
        user: getLoggedInUser(auth),
    };
};

Home = DragDropContext(HTML5Backend)(Home);
export default connect(mapStateToProps)(Home);
Run Code Online (Sandbox Code Playgroud)

单击登录按钮会调用登录功能,但出于某种原因,这thisnull

谢谢参观

ric*_*ilv 7

React不绑定添加到ES6类的方法的上下文,除非它们是标准React生命周期(componentWillReceiveProps,componentDidMount等等)的一部分.

这意味着,你需要手动绑定的价值this为你signUp,logIntogglePanel方法,否则他们申报为箭头的功能,它继承了父上下文.

1.

constructor(props) {
  super(props);
  this.signUp = this.signUp.bind(this);
  this.logIn = this.logIn.bind(this);
  this.togglePanel = this.togglePanel.bind(this);

  this.state = {
    panelIsOpen: false,
    registration: {},
    login: {},
  }
Run Code Online (Sandbox Code Playgroud)

要么

2.

signUp = () => {
  this.props.dispatch(signUp(this.state.registration));

  this.setState({
    registration: {},
  });
}

// the same for logIn and togglePanel
Run Code Online (Sandbox Code Playgroud)

供参考,请参阅文档.