2017-07-29 147 views
2

我想写一个让用户在帖子中移动的东西。所以你看一个特定的帖子,然后你可以去上一个或下一个帖子。我正在尝试使用反应路由器来做到这一点。所以说用户看着posts/3,然后点击NEXT,他或她将被重定向到posts/4,然后看到帖子号。 4.更新路由更改时的组件状态? (react-router)

但是,它还没有工作。点击按钮可以正常工作,并且它也会更改浏览器中的URL。但是,我不知道如何获取新帖子(并重新填充我的currentPost缩减器),只要路由发生变化。

我到目前为止是这样的:

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); 

回答

1

你要找的生命周期方法是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将为您处理剩下的问题。