我通过构建一个简单的博客应用程序来学习React路由器,但我立即被卡住了一个简单的Previous Post和Next Post按钮功能。我的第一个路由器看起来像这样:
<Route path="/" component={App}>
<IndexRoute component={Posts} />
<Route path="posts/:id" component={PostView} />
</Route>
文章:
componentDidMount() {
const { fetchPosts } = this.props.actions;
const url = window.Routes.posts_path({ format: 'json' });
fetchPosts(url);
}
render() {
const { posts, isFetching } = this.props.posts;
const opacity = isFetching ? '0' : '1';
return (
<section className="posts-list post-view" style={{ opacity }}>
{posts.map(post =>
<Post
key={post.id}
id={post.id}
title={post.truncated_title}
content={post.truncated_content}
commentsCount={post.comments.length}
date={post.created_at}
/>
)
}
</section>
);
}
后览:
componentDidMount() {
const { fetchSinglePost } = this.props.actions;
const id = this.props.params.id;
const url = window.Routes.post_path(id, { format: 'json' });
fetchSinglePost(url);
window.scrollTo(0, 0);
}
render() {
***
<footer className="post-footer">
<div className="prv">
<Link to={window.Routes.post_path(`${id - 1}`)}>
← Previous post
</Link>
</div>
<div className="nxt">
<Link to={window.Routes.post_path(`${id + 1}`)}>
Next post →
</Link>
</div>
</footer>
***
);
}
但是路由没有按预期工作:记录了@@router/LOCATION_CHANGE
操作,更改了网址,启动了重新呈现,但没有发生内容更改。我试图让PostView
成为嵌套路线,如下所示:
<Route path="/" component={App}>
<Route path="posts" component={Posts}>
<Route path="/posts/:id" component={PostView} />
</Route>
</Route>
然后在Posts
组件中:
<section className="posts-list post-view" style={{ opacity }}>
{this.props.children ||
posts.map(post =>
<Post
key={post.id}
id={post.id}
title={post.truncated_title}
content={post.truncated_content}
commentsCount={post.comments.length}
date={post.created_at}
/>
)
}
</section>
减速:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import postsReducer from './postsReducer';
export default combineReducers({
routing: routerReducer,
posts: postsReducer
});
初始化:
const store = configureStore();
const routes = configureRoutes(store);
const history = syncHistoryWithStore(
browserHistory,
store
);
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<Provider store={store}>
<Router history={history} children={routes} />
</Provider>, document.getElementById('app'));
}, false);
一般数据流仍然有效,即Posts
在posts.map()
路线上呈现/posts
的结果,并在PostView
路线上呈现/posts/:id
但在两者之间导航来自/posts/:id
内部的PostView
仍然无法正常工作。我已经阅读过关于GitHub的教程,但它并没有真正帮助我,而且我没有想法。我希望能指出如何解决这个问题。如果相关,我也会使用react-router-redux
。