2016-07-11 29 views
0

我有一個單頁的應用程序,我已經定義應用程序中的所有路線,以執行相同的反應組件(使用* -wildcard)導航到他們。星號的Reactjs路由只執行一次

看來組件只會在導航時執行一次。

如何在導航中進行任何更改時調用組件的執行/實例化?

這是我的路線JSX:

<Route path="/" component={App}>  
    {<IndexRoute component={TVPage} />}  
    {<Route path="*" component={TVPage} />} 
</Route> 
+0

你究竟想要做什麼,需要組件重新執行? – erichardson30

+0

每個頁面使用相同類型的組件,並根據url –

回答

1

我認爲當你說你的意思是隻安裝一次「一旦組件只執行」。

既然你沒有顯示你的代碼,我只能假設你已經使用了lifecycle methods之一:componentWillMount | componentDidMount

這些方法只在組件安裝時觸發一次。給定你的路由配置,每當你切換到不同的URL,因爲它使用相同的組件,它不會再次卸載和掛載(因此你的加載邏輯只觸發一次),但如果它的道具已經改變,只需重新渲染。這就是爲什麼你應該插入一個生命週期方法,這個方法在每個支持改變時觸發(比如componentWillReceiveProps)。

試試這個:

class TVPage extends Component { 
 

 
    constructor(props) { 
 
     super(props); 
 
    } 
 

 
    componentWillMount() { 
 
     // Load your data/state (initial) 
 
     this.props.loadMyData(this.props.whatever.data); 
 
    } 
 

 
    componentWillReceiveProps(nextProps) { 
 
     if (this.props.whatever.myStatus !== nextProps.whatever.myStatus) { 
 
      // Load your data/state (any page change) 
 
      nextProps.loadMyData(nextProps.whatever.data); 
 
     } 
 
    } 
 

 
    render() { 
 
     // Render whatever you want here 
 
    } 
 
}

componentWillMount將觸發安裝(初始負載),並componentWillReceiveProps將至少你的道具更改每次觸發。

0

看看下面這個例子使用查詢參數反應路由器:https://github.com/reactjs/react-router/blob/master/examples/query-params/app.js

在你TVPage組件內部的componentDidMount功能,我會得到的數據作爲PARAMS傳遞然後在URL中更新組件的狀態。每當組件內的狀態發生變化時,它就會自動重新加載。

例成分:

class TVPage extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     data: null 
    } 
    } 

    componentDidMount() { 
    // from the example path /TVPage/:id 
    let urlData = this.props.params.id; 
    this.setState({data: urlData}) 

    } 

    render() { 
    return (
     <div> 
     {this.state.data} 
     </div> 
    ); 
    } 

} 
+0

中的數據採取不同的行爲。我沒有在您的示例中看到「componentDidMount」 –

+0

使用cdm函數更新 – erichardson30

+0

這不起作用。 componentDidMount僅在組件安裝時調用一次。 – jdebon