【问题标题】:Update component state on route-change? (react-router)在路由更改时更新组件状态? (反应路由器)
【发布时间】:2018-01-05 18:35:01
【问题描述】:

我正在尝试编写一个让用户在帖子中移动的东西。因此,您查看特定帖子,然后可以转到上一个或下一个帖子。我正在尝试使用反应路由器来做到这一点。假设用户查看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);

【问题讨论】:

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


    【解决方案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 将为您处理剩下的事情。

    【讨论】:

    • componentWillReceiveProps 现在使用不安全
    猜你喜欢
    • 1970-01-01
    • 2018-06-18
    • 2019-07-07
    • 2019-06-14
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2017-12-23
    相关资源
    最近更新 更多