简体   繁体   中英

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. 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. 4.

However, it does not work yet. Clicking the buttons works fine, and it also does change the URL in the browser. However, I do not know how I can then fetch a new post (and populate my currentPost reducer anew), whenever the route changes.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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