[英]React Router <Component/> vs {Component}
我有项目清单。 当用户单击其中一项时,它将带他到只有此元素的页面。 像这样:
Questions
部分:
render() {
return (
<section id='loopContainer' className='display-question'>
<div className='wrapper'>
<ul style={{listStyleType: 'none'}}>
{
this.state.questions.map(question => {
return (
<li key={question.id}>
<h3>Kategoria: {question.category}</h3>
<p>Poziom: {question.level}</p>
<p>Punkty: {question.pointAmount + question.pointBoost}</p>
<img alt='' style={{width: '20%'}} src={question.photoURL}/>
<p>{question.workText}</p>
<Link to={`/question/${question.id}`}
style={{display: 'block', margin: 'auto'}}>Rozwiaz to zadanie
</Link>
</li>
)
})
}
</ul>
</div>
</section>
)
}
Question
部分:
render() {
return (
this.state.questions.map(question => {
return (
<section key={question.id} className='display-question'>
<div className='wrapper show-grid'>
<h3>Kategoria: {question.category}</h3>
<p>Poziom: {question.level}</p>
<p>Punkty: {question.pointAmount + question.pointBoost}</p>
<Col xs={12} md={6}>
<img alt='' style={{width: '100%'}}
src={question.photoURL}/>{/*Need 100% for the ratio*/}
<p>{question.workText}</p>
</Col>
<Col xs={12} md={6}>
<form onSubmit={this.handleSubmit}>
<textarea name="textAnswer" id="textAnswer" style={{
width: '100%',
height: '50vh',
background: 'white',
color: 'black'
}}/>
<input id="file-upload" type="file"/>
<Button type='submit' style={{display: 'block'}}>Wyslij odpowiedz</Button>
</form>
</Col>
</div>
</section>
)
})
)
}
这就是我试图查询数据库的方式:
const itemsRef = firebase.database().ref('Works')
.orderByChild('firebaseKey')
.equalTo(this.props.match.params.id);
问题出在我的Navigation
组件中。 正是在这里:
<Switch>
<Route exact path="/about" component={AboutComponent}/>
<Route exact path="/questions" render={
() => (firebase.auth().currentUser === null ?
<Redirect to='/'/> : <QuestionsComponent/>)
}/>
<Route exact path='/question/:id' render={
() => (firebase.auth().currentUser === null ?
<Redirect to='/'/> : <QuestionComponent/>)
}/>
<Route exact path="/" component={HomeComponent}/>
</Switch>
所以问题是,当我尝试进入单个元素页面时,这将引发错误:
<Route exact path='/question/:id' render={
() => (firebase.auth().currentUser === null ?
<Redirect to='/'/> : <QuestionComponent/>)
}/>
错误是: TypeError: this.props.match is undefined
。
但是,如果我这样做:
<Route exact path='/question/:id' component={QuestionComponent}/>
一切正常。
那么,为什么第一种方法会出错,而第二种方法又好呢? 我如何使第二种方式起作用?
当您使用渲染道具时,它会为您提供Router道具作为参数,您需要将它们传递给使用它们的自定义组件,例如
<Route exact path="/questions" render={
(props) => (firebase.auth().currentUser === null ?
<Redirect to='/'/> : <QuestionsComponent {...props}/>)
}/>
如果是component
道具,Route会自动将路由器道具传递到基础组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.