最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Router where to use AJAX - Stack Overflow

programmeradmin7浏览0评论

I am working on a project using React Router, and I'm having some problems with the data flow.

On every page there is an AJAX call that gets the data for the ponent. I have been putting them in ponentDidMount:

// Below code is written in ES6
ponentDidMount(){
  $.get(someURL, (data)=>{
    this.setState({data:data})
  })
}

Although this works on initial load, it does not get called again when the url changes (a manual refresh is needed). I cannot seem to find a proper life cycle to place the AJAX calls.

Someone please enlighten me with the proper approach to getting data in React Router.

I am working on a project using React Router, and I'm having some problems with the data flow.

On every page there is an AJAX call that gets the data for the ponent. I have been putting them in ponentDidMount:

// Below code is written in ES6
ponentDidMount(){
  $.get(someURL, (data)=>{
    this.setState({data:data})
  })
}

Although this works on initial load, it does not get called again when the url changes (a manual refresh is needed). I cannot seem to find a proper life cycle to place the AJAX calls.

Someone please enlighten me with the proper approach to getting data in React Router.

Share Improve this question asked May 16, 2015 at 19:19 BenBen 1,56813 silver badges30 bronze badges 1
  • I know, this is old but.. check this one: stackoverflow./questions/30279786/… – ridermansb Commented Mar 21, 2017 at 22:45
Add a ment  | 

1 Answer 1

Reset to default 19

After a bit of searching around, this README ultimately solves the problem.

There are 2 solutions outlined in the document:

  1. Use addHandlerKey={true}:

    <Route handler={User} path="/user/:userId" addHandlerKey={true} />

  2. Use ponentWillReceiveProps instead of ponentDidMount.

    • I ended up using both, ponentDidMount for the initial load, ponentWillReceiveProps for subsequent ones.
    • Since they share the same code, I created a new function _updateState and called it in both lifecycles.

My code now:

class Classes extends React.Component {
  ponentDidMount(){ this._updateState() }
  ponentWillReceiveProps(){ this._updateState() }
  _updateState(){
    $.get(/*Some URL*/, (data)=>{
      this.setState({data:data})
    })
  }
}
发布评论

评论列表(0)

  1. 暂无评论