路由更改时更新组件状态? (反应路由器)

时间:2017-07-29 22:34:12

标签: javascript reactjs redux react-router react-redux

我正在尝试编写一个允许用户浏览帖子的内容。所以你看一个特定的帖子,然后你可以去上一篇或下一篇文章。我试图用反应路由器做这个。所以说用户查看posts/3,然后单击“下一步”,他或她将被重定向到posts/4,然后查看帖子号。 4。

然而,它还没有奏效。单击按钮工作正常,它也会更改浏览器中的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 个答案:

答案 0 :(得分: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会为你处理剩下的事情。

相关问题