我试图router从我的组件中访问我的,它是未定义的。这是我的router:
React.render(
<Provider store={store}>
{() =>
<Router>
<Route path="/" component={LoginContainer} />
</Router>
}
</Provider>,
document.getElementById('app')
);
这是容器:
class LoginContainer extends React.Component {
constructor() {
super();
}
static propTypes = {
handleLogin: PropTypes.func.isRequired
}
static contextTypes = {
router: React.PropTypes.object
}
handleLogin() {
this.props.dispatch(Actions.login(null, null, this.context.router));
}
render() {
return (
<Login
auth={this.props}
handleLogin={this.handleLogin}
/>
);
}
}
function mapStateToProps(state) {
return {
stuff: []
}
}
export default connect(mapStateToProps)(LoginContainer);
最后是组件:
import React, { PropTypes } from 'react';
class Login extends React.Component {
static propType = {
handleLogin: PropTypes.func.isRequired
}
static contextTypes = {
router: React.PropTypes.object
}
render() {
return (
<div className="flex-container-center">
<form>
<div className="form-group">
<button type="button" onClick={this.props.handleLogin}>Log in</button>
</div>
</form>
</div>
);
}
}
module.exports = Login;
当我点击login按钮时,它会点击handleLogin容器中的 。在 myhandleLogin中,我的this值是undefined。我已经尝试绑定this到中的函数constructor,但它仍然是undefined。
此外,当我在render函数中放置断点时,我有一个this.context.router,但它是undefined. 我怎样才能得到我的this正确,handleLogin以及如何确保我有我router的context,但它不是undefined?