[英]Update component state on route-change? (react-router)
我正在嘗試寫一篇能讓用戶在帖子中移動的東西。 因此,您查看特定的帖子,然后可以轉到上一個或下一個帖子。 我正在嘗試用React Router做到這一點。 假設用戶查看了posts/3
,然后單擊NEXT,他或她將被重定向到posts/4
,然后看到職位號。 4。
但是,它尚不起作用。 單擊按鈕可以正常工作,並且也可以在瀏覽器中更改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);
您正在尋找的生命周期方法是componentWillReceiveProps
大致是這樣的:
class Component extends React.Component {
componentWillReceiveProps(nextProps) {
const currentId = this.props.id
const nextId = nextProps.id
if (currentId !== nextId) {
this.props.fetchPost(nextId)
}
}
}
從那里,我認為Redux / React將為您處理其余的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.