我的App.js中有一个包含3个预填充条目的州。我创建了一个组件,让用户添加一个新条目并将其添加到状态。
我有一个额外的组件,我可以在单独的页面中查看条目的详细信息。
所以App.js有以下内容:
class App extends Component {
constructor(props){
super(props);
this.state = {
articles: [
{
"id" : 0,
"title": "Entry 1",
"content": "Nonsense, nonsense, nonsense."
},
{
"id": 1,
"title": "Entry 2",
"content": "More nonsense."
},
{
"id": 2,
"title": "Entry 3",
"content": "Even More Nonsense"
}
],
nextArticleId : 3
}
this.handleSave = this.handleSave.bind(this);
}
handleSave(article) {
this.setState((prevState, props) => {
const newArticle = {...article, id: this.state.nextArticleId};
return {
nextArticleId: prevState.nextArticleId+1,
articles : [...this.state.articles, newArticle]
}
})
}
render(){
return(
<BrowserRouter>
<div>
<Header />
<Route exact path="/" component={(props)=> <ArticleList {...props} articles={this.state.articles}/>}/>
<Route exact path='/article/:id' render={(props) => <ArticleView {...props} articles={this.state.articles} />}/>
<Route path='/create' component={(props)=> <ArticleMaker {...props} articles={this.state.articles} onSave={this.handleSave} />}/>
</div>
</BrowserRouter>
)
}
}
export default App;
然后我将状态传递给articleMaker组件,该组件在提交后将数据保存到状态。然后列表显示新条目,但是当我单击新条目时,我得到错误的标题和内容未定义:
class ArticleView extends Component {
render() {
let {id} = (this.props.match.params);
id = Number(id);
let Article = this.props.articles.filter((matcher) => (
matcher.id === id
))
let {title, content} = Article[0];
return(
<div className="container">
<div>{title} {content}</div>
</div>
)
}
}
export default ArticleView;