我试图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
了容器中的。在我看来handleLogin
,我的this
价值是undefined
。我试图绑定this
到中的函数constructor
,但仍然如此undefined
。
另外,当我在render
函数中设置断点时,我有一个this.context.router
,但它是undefined
。如何让我的this
在我的正确handleLogin
,以及如何我确保我有我router
的context
,这是不是undefined
?
保持更改的最佳方法是浏览“发行”页面。
在阵营是路由器版本> 1.0.0-beta3
和< 2.0.0-rc2
,没有context.router
。相反,您需要寻找context.history
。
如果使用版本<= 1.0.0-beta3
或>= 2.0.0-rc2
,则context.router
在那里。简而言之,发生了什么事,它被删除了,history
但是维护者决定最好将历史库API隐藏在路由器后面,因此他们router
在2.0 RC2及更高版本中使用了上下文。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句