我目前正开始使用react,并有两条定义为这样的路线:
<Route path='/articles' component={ArticlesIndex} />
<Route path='/articles/create' component={ArticlesCreate} />
访问/articles
时,只有我的ArticlesIndex
组件会按预期呈现。但是,导航到/articles/create
时,尽管我的ArticlesIndex
组件没有引用ArticlesCreate
,但我的ArticlesCreate
和ArticlesIndex
组件都在页面上呈现。由于路由包含在ArticlesIndex
中,因此React Router似乎正在渲染articles/create
组件。
我该如何克服?
出于完整性考虑,这是我的两个组成部分:
ArticlesIndex
组件:
import React, { Component } from 'react'
export class ArticlesIndex extends Component {
displayName = ArticlesIndex.name
constructor(props) {
super(props)
this.state = { articles: [], loading: true }
fetch('https://localhost:44360/api/Articles/')
.then(response => response.json())
.then(data => {
this.setState({ articles: data, loading: false })
})
}
static renderArticlesTable(articles) {
return (
<table className="table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{articles.map(article => (
<tr key={article.id}>
<td>{article.id}</td>
<td>{article.title}</td>
<td>{article.description}</td>
</tr>
))}
</tbody>
</table>
)
}
render() {
let contents = this.state.loading ? (
<p>
<em>Loading...</em>
</p>
) : (
ArticlesIndex.renderArticlesTable(this.state.articles)
)
return (
<div>
<h1>Articles</h1>
{contents}
</div>
)
}
}
和ArticlesCreate
组件:
import React, { Component } from 'react'
export class ArticlesCreate extends Component {
displayName = ArticlesCreate.name
constructor(props) {
super(props)
this.state = {
title: '',
description: '',
}
this.handleSubmit = this.handleSubmit.bind(this)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group row">
<label className=" control-label col-md-12" htmlFor="Title">
Title
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="title"
defaultValue={this.state.title}
required
/>
</div>
</div>
<div className="form-group row">
<label className=" control-label col-md-12" htmlFor="Description">
Description
</label>
<div className="col-md-4">
<input
className="form-control"
type="text"
name="description"
defaultValue={this.state.description}
required
/>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-default">
Save
</button>
</div>
</form>
)
}
handleSubmit(event) {
event.preventDefault()
const data = new FormData(event.target)
// POST request for Add employee.
fetch('https://localhost:44360/api/Articles/', {
method: 'POST',
body: data,
})
.then(response => response.json())
.then(responseJson => {
this.props.history.push('/articles')
})
}
}
答案 0 :(得分:2)
您忘记在exact
上添加<Route />
道具,而网址/articles/create
与两条路线都匹配。
将exact={true}
或exact
传递到<Route/>
props
中时,如果location.pathname
完全匹配您path
。
<Route exact={true} path='/articles' component={ArticlesIndex} />
<Route path='/articles/create' component={ArticlesCreate} />