2017-03-26 73 views
-1

我如何在AppContainer和Home組件之間共享狀態將容器組件中的道具傳遞給嵌套的路由組件

例如,我想將結果對象置於AppContainer狀態以將其傳遞給所有其他組件。

在這個程序中,我沒有使用Redux。

我試着使用React.cloneElement在AppContainer但產生一個錯誤:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

index.js

<Router history={browserHistory}> 
    <AppContainer> 
     <Route path="/" component={Home} /> 
     <Route path="search" component={Search} /> 
    </AppContainer> 
</Router> 

AppContainer.js

render() { 

    return (
      <div className="containerApp"> 

       {this.props.children} 

      </div> 
    ); 
} 
+0

一般來說,這是不是從最佳實踐的立場點(特別是因爲你不使用終極版)。可你給的你是什麼樣的想法是個好主意試圖完成?更有可能的是,比通過路由器傳遞狀態更好。 – Teedub

+0

好的。謝謝。例如在家庭組件我有一個搜索表單,我檢索結果,然後我將這個結果添加到組件狀態。但我想在搜索組件中得到這個結果。告訴我,如果我有更好的解釋... –

+0

我不認爲你可以將狀態從父組件傳遞到子組件的狀態,無論是使用上下文(這很麻煩),或者你將狀態作爲道具傳遞給子組件。這很容易做到。爲什麼複雜的事情:P –

回答

0

React.cloneElement是正確的路要走。例如:

render() { 
    const childProps = { 
     prop1: this.state.prop1 
    } 
    return (
      <div className="containerApp"> 

       {React.cloneElement(this.props.children, childProps)} 

      </div> 
    ); 
} 

如果這給你,你以前收到錯誤,然後我能想到的唯一理由是,AppContainer被之前的任何路由匹配渲染沒有任何子女。您可以通過在AppContainer有條件地渲染或者減輕這樣的:

render() { 
    const childProps = { 
     prop1: this.state.prop1 
    } 

    const { children } = this.props; 
    return (
      <div className="containerApp"> 

       {children && React.cloneElement(children, childProps)} 

      </div> 
    ); 
} 
相關問題