我正试图从我的组件中访问我的router
,它是未定义的。这里是我的router
:为什么我的反应组件中的context.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
容器。在我的handleLogin
中,我的this
值是undefined
。我试图将this
绑定到constructor
中的函数,但它仍然是undefined
。
此外,当我在我的render
函数中放置断点时,我有一个this.context.router
,但它是undefined
。我如何在我的handleLogin
中获得我的this
正确,以及如何确保我的在context
上,而不是undefined
?
我有一个预感,这个建议是过时的。我正在使用react-router版本2.0.0-rc5,并且我收到警告,表明情况正好相反。它促使我使用context.router而不是context.history。你能否介绍一下这方面的情况?谢谢! – Ryan
@Ryan有同样的感觉,并可以验证'context.history'已被弃用。 'context.router'是首选。对我来说,我只需在'contextTypes'中用'router'替换'history'。 – sighrobot
@sighrobot谢谢,我更新了答案。 –