我想编写一个程序,让用户可以在文章中进行前后翻阅。当用户查看某篇文章时,可以通过单击“下一篇”按钮来重定向到下一篇文章(例如从“posts/3”到“posts/4”),并查看相应的文章内容。我试图使用React Router实现这个功能。但是目前它还不能正常工作。点击按钮没问题,浏览器的URL也会更改。但是我不知道如何在路由变化时获取新的文章(并更新currentPost reducer的值)。 目前我的代码如下:
import React from 'react'
import {connect} from 'react-redux'
import {fetchPost} from '../actions/currentPost.js'
class PostView extends React.Component {
constructor(props) {
super(props);
this.setNextPost = this.setNextPost.bind(this);
this.setPreviousPost = this.setPreviousPost.bind(this);
}
componentDidMount() {
const {id} = this.props.match.params;
this.props.fetchPost(id);
console.log("HELLO");
}
setPreviousPost() {
var {id} = this.props.match.params;
id--;
this.props.history.push('/Posts/1');
}
setNextPost() {
var {id} = this.props.match.params;
id++;
this.props.history.push('/Posts/'+id);
}
render() {
return (
<div>
<h1>Here is a Post</h1>
<button onClick={this.setPreviousPost}>Previous</button>
<button onClick={this.setNextPost}>Next</button>
</div>
);
}
}
function mapStateToProps (state) {
return {
currentPost: state.currentPost
};
}
export default connect(mapStateToProps, {fetchPost})(PostView);