2016-04-24 102 views
2

我有一個PageBuilder組件,根據配置文件動態構建編輯/列表頁面。我想要使​​用相同的PageBuilder組件的動態路由(如「/ collection/list」,「/ collection/edit/123123」,「/ dashboard」等)。 我無法正常工作 - 例如,如果我在/收藏/列表中,點擊鏈接到/ collection/edit/1231時不起作用。只有對該URL的刷新纔有效(反之亦然)。 我試着把我的初始化代碼PageBuilder的componentWilLReceiveProps,但它似乎每秒鐘都會調用它。 我的路線是這樣的: <Route path="/" component={App}> <IndexRedirect to="/dashboard" /> <Route path="/:page/:collection/:action(/:entity_id)" component={PageBuilder} /> <Route path="/:page" component={PageBuilder} /> </Route> 使用相同的組件用於不同的路由與反應路由器

而且我PageBuilder:

constructor(props) { 
    super(props); 
    this.createSectionsHTML = this.createSectionsHTML.bind(this); 
    this.onChange = this.onChange.bind(this); 
    this.onSave = this.onSave.bind(this); 
} 

getPageName() { 
    return this.props.params.page.replace(/-/g, '_').toLowerCase(); 
} 

componentWillReceiveProps(props) { 
    this.action = this.props.params.action; 
} 

componentWillMount() { 
    let pageName = this.getPageName(); 
    this.props.dispatch(setInitialItem(pageName)); 
} 

componentDidMount() { 

    let pageName = this.getPageName(); 
    let { collection, entity_id } = this.props.params; 

    if (collection && entity_id) { 
     let { dispatch } = this.props; 
     dispatch(getCollectionEntity(collection, entity_id, pageName)); 
    } 
} 

如何給每個我重定向到一個不同的路線時重新渲染頁面的任何想法?如果我可以在重定向時卸載並重新安裝組件,那將是非常好的,但我不知道如何去告訴React Router這樣做......

謝謝!

回答

6

使this.state這樣它將控制你的組件如何呈現。

現在,內componentWillReceiveProps,檢查nextProps參數

componentWillReceiveProps(nextProps, nextState) { 
    if(<check in nextProps if my route has changed>) { 
    let newState = Object.assign({}, this.state); 
    // make necessary changes to the nextState Object by calling 
    // functions which would change the rendering of the current page 
    this.setState({ nextState }); 
    } 
} 

這將使componentWillReceiveProps採取行動路線的變化,只有當。

在渲染功能

現在,

render() { 
    const { necessary, variables, to, render } = this.state; 
    let renderVariables = this.utilityFunctionsReqToRender(someArgs); 
    return (
    <toRenderJsx> 
     ... 
    </toRenderJsx> 
) 
} 

這將使你的組件「刷新」每當路由變化。

+0

謝謝!我的頁面構建器的工作方式並不是真的依賴''this.state'',但我可以改變它,以便它(我爲我的應用程序範圍使用Redux)。我用這種方法遇到的另一個問題是,我知道我的位置何時更改,但是如果我要刷新頁面,我無法知道我「更改了」路線(因爲「nextProps」和「 this.props''顯然是相同的...) 但我會嘗試玩這個解決方案,我認爲這是一個很好的起點。謝謝! – user1595077

+0

很酷,我通過改變渲染來更多地依賴''this.state''來獲得這個工作(呃,有一些小問題,但路由工作!)。謝謝! – user1595077