我试图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
?