简体   繁体   English

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

[英]Update component state on route-change? (react-router)

I am trying to write a thing that lets the user move through posts. 我正在尝试写一篇能让用户在帖子中移动的东西。 So you look at a particular post, and then you can go to the previous or next post. 因此,您查看特定的帖子,然后可以转到上一个或下一个帖子。 I am trying to do this with react router. 我正在尝试用React Router做到这一点。 So say the user looks at posts/3 , then by clicking NEXT he or she will be redirected to posts/4 and then see post no. 假设用户查看了posts/3 ,然后单击NEXT,他或她将被重定向到posts/4 ,然后看到职位号。 4. 4。

However, it does not work yet. 但是,它尚不起作用。 Clicking the buttons works fine, and it also does change the URL in the browser. 单击按钮可以正常工作,并且也可以在浏览器中更改URL。 However, I do not know how I can then fetch a new post (and populate my currentPost reducer anew), whenever the route changes. 但是,我不知道每当路线更改时如何获取新帖子(并重新填充currentPost reducer)。

What I have so far is this: 我到目前为止所拥有的是:

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

The lifecycle method you're looking for is componentWillReceiveProps 您正在寻找的生命周期方法是componentWillReceiveProps

Here's more or less what it would look like: 大致是这样的:

class Component extends React.Component {
  componentWillReceiveProps(nextProps) {
    const currentId = this.props.id
    const nextId = nextProps.id

    if (currentId !== nextId) {
      this.props.fetchPost(nextId)
    }
  }
}

from there, I think Redux/React will handle the rest for you. 从那里,我认为Redux / React将为您处理其余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM