【发布时间】:2016-09-06 08:46:03
【问题描述】:
我正在尝试在客户端使用 react 和 redux 构建 CRUD 应用程序,但我被这个问题困扰了好几个星期。
我有 2 个主要组件:一个用于文章列表,另一个用于文章。
我正在向检索数据的服务器调用带有 componentDidMount 的 AJAX 获取请求:
class Category1 extends React.Component {
componentDidMount(){
this.props.fetchArticles();
}
render() {
return (
<div>
{this.props.children ||
<div className="mainContent">
<h1>Category1</h1> <hr />
<ListContainer articles={this.props.articles}/>
</div>
}
</div>
);
}
}
在 ListContainer 中,我在列表上迭代数据并使用 <Link> 呈现它们,如下所示:
export default class ListContainer extends React.Component {
renderItem(article){
return (
<Link to={"/articles/" + article.id} key={article.id} >
<ItemContainer article={article} />
</Link>
)
}
render(){
<div className="row">
<div className="col-lg-8 col-md-8 col-sm8">
{this.props.articles.map(this.renderItem.bind(this))}
</div>
</div>
}
}
当我点击列表中的一篇文章时,它会将我带到一个文章页面,该页面也使用 componentDidMount 来检索其文章的数据。
文章页面组件:
class ArticlePage extends React.Component {
componentDidMount(){
this.props.fetchArticle(this.props.params.id);
}
render() {
return (
<div className="row">
<div className="col-lg-6 col-md-6 col-sm6">
<div className="article-content">
<h2>{this.props.article.title}</h2>
<div className="article-body">
<p>{this.props.article.image}</p>
<p>by {this.props.article.name}</p>
</div>
</div>
</div>
</div>
);
}
}
我的问题是访问 ArticlePage 后,我无法返回上一页或从该页面转到其他页面。即使路径会更改,它也会保留在同一页面中,并且我收到一个控制台错误,提示“this.props.articles.map 不是一个函数”,而 ArticlePage 没有。我确信它的错误来自 ListContainer。此外,当我重新加载 ArticlePage 时,它的组件就会消失而不会出现任何错误。
这是我的路线:
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="login" component={LoginPage}/>
<Route path="signup" component={SignupPage}/>
<Route path="submit" component={auth(SubmitPage)}/>
<Route path="category1" component={Category1}>
<Route path="articles/:id" component={ArticlePage} />
</Route>
<Route path="category2" component={Category2}>
<Route path="articles/:id" component={ArticlePage} />
</Route>
</Route>
我该如何解决这个问题?
【问题讨论】:
-
请发布您的路由设置,因为解决此问题很重要。
-
我刚刚添加,但我认为我的路线设置没有问题
标签: reactjs redux react-router