【问题标题】:React remount on Router change对路由器更改做出反应重新安装
【发布时间】:2019-11-27 11:22:28
【问题描述】:

我在 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 路由器版本。

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    这样做。检查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()
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多