情况如下: 我有一个Navigation
, 和Login
组件。Login
只是一个导出的函数,它让用户登录。它是这样的:
export function login() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
document.getElementById('close').click();
document.getElementById('questions').click();
}
).catch(e => console.log(e));
}
这几乎完美无缺。
这是我的Navigation
组件
render() {
return (
<BrowserRouter>
<React.Fragment>
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link id='home' to="/">UczIchApp</Link>
</Navbar.Brand>
</Navbar.Header>
<Nav>
<LinkContainer id='about' to='/about'>
<NavItem>O nas</NavItem>
</LinkContainer>
{// The issue starts here
this.state.user ?
<React.Fragment>
<LinkContainer id="questions" to='/questions'>
<NavItem>Zadania</NavItem>
</LinkContainer>
<NavItem onClick={logout.bind(this)}>Wyloguj się</NavItem>
</React.Fragment>
:
<NavItem onClick={this.openLogin}>Zaloguj się</NavItem>
}
</Nav>
</Navbar>
<Switch>
<Route exact path="/about" component={AboutComponent}/>
<Route exact path="/questions" component={QuestionsComponent}/>
<Route exact path="/" component={HomeComponent}/>
<Route path='/question/:id' component={QuestionComponent}/>
</Switch>
<ModalComponent show={this.state.show} changeShowState={this.changeShowState}/>
</React.Fragment>
</BrowserRouter>
)
}
所以当我登录用户时,我希望他被转移到Questions
路由中。我正在尝试通过点击来做到这一点。但问题是,Questions
链接尚未呈现,所以我收到:TypeError: "document.getElementById(...) is null"
错误。
我怎样才能让它等到组件被渲染?
您可以以编程方式重定向用户。有几种方法可以做到这一点,例如:
如果您的Login
组件扩展,React.Component
您可以访问history
像这样的对象:
class Login extends React.Component {
// use `this.props.history.push('/some/path')` here
};
因此,您可以在登录时传递this.props.history
给您的login
函数并调用push
:
export function login(history) {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
history.push('/questions');
}
).catch(e => console.log(e));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句