我正試圖從我的組件中訪問我的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謝謝,我更新了答案。 –