2016-08-05 55 views
2

我正在使用ReactJS中的實時儀表板應用程序來監視傳感器。我在PHP上使用AutobahnJS + Websockets來傳輸數據。ReactJS:傳輸道具

這是我的儀表板在組件視圖中的抽象。 Abstraction of dashboard in component view

Main.jsx:

class Main extends React.Component { 
constructor(props) { 
    super(props) 
} 

componentDidMount() { 
    $(document).foundation(); 

    var that = this; 

    var conn = new ab.Session('ws://xx.xxx.xxx.xx', function() { 
     conn.subscribe('', function(topic, data) { 
      console.log(data); 
      that.setState({ 
       result: data 
      }); 
     }); 
    }, function() { 
     console.warn('WebSocket connection closed'); 
    }, {'skipSubprotocolCheck': true}); 
} 
render() { 

    return (
     <div> 
      <div className="off-canvas-wrapper"> 
       <div className="off-canvas-wrapper-inner" data-off-canvas-wrapper> 
        <div className="off-canvas position-right" data-position="right" id="offCanvas" data-off-canvas> 
         <SensorDetails/> 
        </div> 

        <div className="off-canvas-content" data-off-canvas-content> 
         <Nav/> 

         <div className="row"> 
          <div className="columns medium-12 large 12"> 
           {this.props.children} 
          </div> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    ); 
} 
}; 

module.exports = Main; 

什麼是道具傳遞從Main.jsx到BuildingList.jsx的正確方法?我曾嘗試更換:

{this.props.children} 

<Dashboard data={this.state.result}/> 

這工作,但我無法訪問例如我的鏈接帳號設定。我的反應路由器設置如下:

<Router history={hashHistory}> 
    <Route path="/dashboard" component={Main} > 
     <Route path="/about" component={About} onEnter={requireLogin}/> 
     <Route path="/examples" component={Examples} onEnter={requireLogin}/> 
     <Route path="/accountSettings" component={AccountSettings} onEnter={requireLogin}/> 
     <IndexRoute component={Dashboard}/> 
    </Route> 
    <Route path="/" component={Login} onEnter={redirectIfLoggedIn}/> 
</Router> 

我該如何解決這個問題?謝謝。

回答

1

好,反應的目的是從上往下傳遞道具..

它使數據管理真的很辛苦,因爲你可以有很多這就需要相同的數據的組件。

所以它最好使用某種Flux Architecture(例如Redux) 或更簡單的數據層(如Mobx)。

你應該看看每個因爲他們有很大的不同,但旨在幫助您與數據管理,(特別是)在陣營

3

有一對夫婦的方式來處理這個問題。

您可以使用的一種方法是像Main.jsx一樣渲染您的孩子。傳遞兩個道具給你的孩子(狀態和updateState)。

{React.Children.map(this.props.children, (child) => { 
    return React.cloneElement(child, { 
     state: this.state, 
     updateState: (state) => this.setState(state) 
    }); 
}} 

從你的子組件,你可以通過調用這個來更新Main.jsx的狀態。

this.props.updateState({prop: 'value'}) 

我不認爲這是在React中做事的最佳方式。我更喜歡採取事件方法。我通常會有類似以下的內容來偵聽和更新「全局可用狀態」。 Main.jsx的

componentDidMount() { 
    App.Event.on('state.update', (state = {}) => this.setState(state)); 
} 

App.Event是一個簡單的事件系統,您可以通過觸發事件,像這樣調用。

App.Event.fire('state.change', {prop: 'value'}); 
+0

謝謝Enjijar!我已經嘗試了兩種解決方案,但都沒有工作。對於第二種解決方案,我收到「應用程序未定義」錯誤。 –