首页 > 解决方案 > 对路由器更改做出反应重新安装

问题描述

我在 reactjs 中有一个简单的 post 组件,该组件根据 id 从 db 打印 post 数据,id 是从 url 中挑选的(我为此使用 react 路由器),并且数据是由 ajax 调用挑选的。问题是,当我更改页面组件不更新内容时,更新仅在我刷新页面时发生。

class Post extends Component {

  constructor(props) {
    super();

    this.state = {
      thePost: '',
    };
  }

  componentDidMount(){
axios.get(endpoint.posts+'/getpost/'+this.props.match.params.id, cfg)
            .then(res => {
                this.setState({
                    thePost: res.data.thePost || ''
                });
        })      
  }

  render () {
    return (
        <div>POST { this.props.match.params.id } - { JSON.stringify(this.state.thePost, null, 0) }</div>
    )
  }
}

export default Post;

现在的问题是每次页面更改都不会调用 componentDidMount,我如何强制重新安装?或者我需要在组件的其他生命周期部分中移动 ajax 调用?

我发现了一些类似的问题,但太老了,尊重实际的 reactjs 和 react 路由器版本。

标签: reactjsaxios

解决方案


像这样做。componentDidUpdate如果当前 url 与之前的不匹配,请检查 url 更改再次发出 API 请求。

  componentDidMount(){
    this.getPosts()
  }

  getPosts = () => {
    axios.get(endpoint.posts+'/getpost/'+this.props.match.params.id, cfg)
      .then(res => {
        this.setState({
            thePost: res.data.thePost || ''
        });
    })
  }

  componentDidUpdate(prevProps) {
    if (this.props.match.params.id !== prevProps.match.params.id) {
      this.getPosts()
    }
  }

推荐阅读