2016-06-10 50 views
0

我有一個基於狀態屬性打開和關閉的模式的容器組件。使用react-router設置來自URL的狀態屬性

我想通過URL來控制這一點,即我想有

/projects - the modal is NOT open 
/projects/add - the modal IS open 

除了能夠直接鏈接到它,我想要的網址更改當我點擊中的主要環節容器打開模式。

有人能解釋我該如何做到這一點,或指出我在一個好的教程的正確方向?

+0

你可以通過'this.props.params'直接訪問'params'和'pathname',也許直接引用它來管理模態。 – Kujira

回答

0

注意:這種方式並不完美。更多的是它比模式更反對模式。我在這裏發佈它的原因是它適合我,我喜歡我可以添加模式的方式(我可以將模式添加到任何頁面,並且通常它們的組件不依賴於其他應用程序,而且我保持良好網址而不是醜陋的?modal=login-form)。但在你發現一切正常之前,準備好解決問題。仔細想想!

讓我們考慮你想要以下網址:

  • /users顯示<Users />組件

  • /users/login顯示<Users />組件和<Login />模式在它

你想Login不取決於無論如何說,,說添加登錄模態到其他頁面沒有痛苦。

讓我們考慮一下,你有一個根構件站在其他組件之上。例如Usersrender可能是這個樣子:

render() { 
    return (
    <Layout> 
     <UsersList /> 
    </Layout> 
); 
} 

而且Layoutrender可能是這個樣子:

render() { 
    return (
    <div className="page-wrapper"> 
     <Header /> 
     <Content> 
     {this.props.children} 
     </Content> 
     <Footer /> 
    </div> 
); 
} 

訣竅是,每次我們需要時間模式的注入以武力<Layout />

最簡單的方法是使用助焊劑。我使用的是redux,並且有ui reducer用於這種頁面元信息,如果您使用其他通量實現,則可以創建ui商店。無論如何,最終目標是渲染模態,如果<Layout />的狀態(或甚至更好的道具)包含modal等於表示模態名稱的某個字符串。喜歡的東西:

render() { 
    return (
    <div className="page-wrapper"> 
     <Header /> 
     <Content> 
     {this.props.children} 
     </Content> 
     {this.props.modal ? 
     <Modal key={this.props.modal} /> : 
     null 
     } 
     <Footer /> 
    </div> 
); 
} 

<Modal />回報模式組件依賴於給定鍵(在我們login-form鍵的情況下,我們要接受<Login />組件)。

好吧,讓我們去路由器。考慮下面的代碼片段。

const modal = (key) => { 
    return class extends React.Component { 

    static displayName = "ModalWrapper"; 

    componentWillMount() { 
     // this is redux code that adds modal to ui store. Replace it with your's flux 
     store.dispatch(uiActions.setModal(key)); 
    } 

    componentWillUnmount() { 
     store.dispatch(uiActions.unsetModal()); 
    } 

    render() { 
     return (
     <div className="Next">{this.props.children}</div> 
    ); 
    } 

    } 
}; 

... 
<Route path="users" component={Next}> 
    <IndexRoute component={Users}> 
    <Route path="login" component={modal('login-form')}> 
    <IndexRoute component={Users} /> 
    </Route> 
</Route> 

(不要在意Next - 我在這裏添加它簡單想象一下,它只是呈現this.props.children。)

modal()函數返回反應成分,在ui店觸發變化。因此,一旦路由器獲得/users/login它將login-form添加到ui商店,<Layout />獲取它作爲道具(或狀態)並呈現<Modal />,它呈現對應於給定密鑰模式。

0

要以編程方式評估新URL,請通過router to your component並使用push。例如push將由用戶操作在回調觸發器中調用。

設置路由器時,將路由設置爲/projects/:status。那麼在組件路由中,您可以使用this.props.param.status來讀取status的值。例如,從react-router中讀取「whats-it-look-lik」。