如何重新加载组件对url参数更改做出反应?

时间:2016-06-20 12:50:07

标签: reactjs react-router

我有以下路线: -

ReactDOM.render((
     <Router history={browserHistory}>
      <Route path="/" component={app}>
        <IndexRoute component={home}/>
        <Route path="/articles" component={articles} />
        <Route path="/articles/topics/:featureName" component={filteredArticles} />
      </Route>
    </Router>
), document.getElementById('app'));

现在,当我请求/ articles / topics / topic1时,获取的前5个内容正在使用API​​调用。当用户再次到达页面底部时,将进行API调用,其中将获取下5个内容。这工作正常(请注意,handlecroll函数会检查页面底部,这里有一些小问题,所以现在已经注释掉了。)

现在说我从列表中选择下一个主题,以便更改网址,因此我的网址更改为/ articles / topics / topic2,现在我需要与上面提到的相同的内容并为此主题调用apis。

以下是我当前的组件代码: -

import React from 'react';
import axios from 'axios';
import ArticleList from './ArticleList';
import Banner from './Banner';
import LeftNavBar from './LeftNavBar';
import RightNavbar from './RightNavbar';
import {url} from './Constants';


/*MERGE INTO ARTICLES ONCE SCROLL LOGIC IS FIXED*/
class FilteredArticles extends React.Component{

  constructor(){
    super();
    {/* Adding global event listener,binding it to scroll event and adding it to handleScroll function */}
    /*window.addEventListener("scroll", this._handleScroll.bind(this));*/
    this.state ={
      articles : [],
      loadingFlag:false,
      limit : 5,
      offset :0,
      subFeatureName:[],
      flag: false
    }
  }


  _getContent(){
    let self=this;
    axios.get(url+'/articles/filter/?filter=popular&category='+this.props.params.featureName+'&limit='+this.state.limit+'&offset='+this.state.offset)
    .then(function(response){
        /*Checking if limit has exceeded meta count, if it has stopped we dont call the APIS*/
        if(self.state.limit  >= response.data.meta.total_count){
          self.setState({articles : self.state.articles.concat(response.data.results),
              offset : self.state.limit,
              limit: self.state.limit+self.state.offset,
              subFeatureName: self.props.params.featureName,
              loadingFlag: false}
        )
      }
        else{
          self.setState({articles : self.state.articles.concat(response.data.results),
              offset : self.state.limit,
              limit: self.state.limit+self.state.offset,
              subFeatureName: self.props.params.featureName,
              loadingFlag: true}
            )
        }
    })
    .catch(function(error){
       console.log(error);
    });
  }



  _handleScroll(){
    /*Calling 5 more articles when someone scrolls down and reaches the page end
    const windowHeight = window.innerHeight;
    const scrollT = $(window).scrollTop();
    if(windowHeight- scrollT < 200){
      if(!this.state.loadingFlag){
        this.setState({loadingFlag : true});
        this._getContent();
      }
  }*/
}

  componentDidMount(){
    /*calling _getContent function to get first five articles on page load*/
    console.log("got content");
    this._getContent();
  }

   render(){
     console.log("inside render");
     return(
       <div>
         <Banner title="Article Page"/>
         <div className="content-container">
           <LeftNavBar/>
           <div className ="feeds">
             <div className="card">
               {/* Sending hideSeeAll as prop to remove see all button on main article page*/}
                <ArticleList articles={this.state.articles} hideSeeAll='true' keyword="Top Articles"/>
             </div>
           </div>
           <RightNavbar/>
         </div>
      </div>
   )
 }
}

export default FilteredArticles;

所以基本上我试图理解,如果我有像 / articles / topics /:featureName 这样的路线,我会调用像/ articles / topics / topic1或/ articles / topics / topic2这样的页面,组件是否可以被真实地加载(我需要调用不同的API再次获取内容)。

也就是说,对于/ articles / topics / topic1,调用的API是

/ API / V0 /物品/过滤器/过滤器=流行&安培;类别= TOPIC1&安培;极限= 5&安培;偏移量= 0

和/ articles / topics / topic2调用的API是

/ API / V0 /物品/过滤器/过滤器=流行&安培;类别=标题2&安培;极限= 5&安培;偏移量= 0

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:6)

你不应该以这种方式查询API /更新组件状态,但完全是另一个问题。也许考虑使用Flux方法。

无论如何,您可以使用 componentWillReceiveProps(nextProps)生命周期方法接收路由器nextProps参数并再次查询您的API:

componentWillReceiveProps(nextProps) {
    this._getContent(nextProps.params.featureName);
}

_getContent(featureName) {
 ...query your API
}

答案 1 :(得分:2)

此外,如果你正在使用Redux,请进行这样的检查以避免无限循环:

componentWillReceiveProps(newProps) {
    if (this.props.someValue === newProps.someValue) {
        this.props.fetchSomething(newProps.params.somethingName);
    }
}