在路由变化时更新组件状态?(React-Router)

4
我想编写一个程序,让用户可以在文章中进行前后翻阅。当用户查看某篇文章时,可以通过单击“下一篇”按钮来重定向到下一篇文章(例如从“posts/3”到“posts/4”),并查看相应的文章内容。我试图使用React Router实现这个功能。但是目前它还不能正常工作。点击按钮没问题,浏览器的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);
1个回答

2

你要找的生命周期方法是 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会为您处理其余部分。

1
componentWillReceiveProps现在已经不安全使用了。 - clever_bassi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接