2017-02-19 50 views
0

我正在使用ReactJS進行SPA。我有一個根組件應用程序,然後有幾個子組件。在App組件中,我試圖存儲一些應用程序級別的狀態,例如登錄用戶標識和其他數據。但是我沒有看到我的狀態被傳播下來的子組件。ReactJS在組件之間傳播數據

應用

import { Router, Route, Link, IndexRoute, browserHistory, hashHistory } from 'react-router'; 
import ParameterContainer from './components/parameter/parameter-container'; 
import NavMenu from './components/navigation/nav-menu'; 
import {Alert} from 'react-bootstrap'; 
import SelectFilter from './components/sample/sample-container'; 

// Main component and root component 
export default class App extends React.Component { 

    constructor(props) { 
     super(props); 
     this.state = { 
      userId: null, 
      roles: null, 
      parameterTypes: { 
       'STRING': 'STRING', 
       'BOOLEAN': 'BOOLEAN', 
       'INTEGER': 'INTEGER', 
       'DECIMAL': 'DECIMAL' 
      } 
     }; 
    } 

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

// page for 404 
class NoMatch extends React.Component { 
    render() { 
     return (
      <div className="container"> 
       <Alert bsStyle="danger"> 
        <h1>404: Not Found</h1> 
        <h3>The requested resource does not exist!</h3> 
       </Alert> 
       <img src="images/404.png" style={{display: 'block', margin: '0 auto', width: 300, height: '*'}} /> 
      </div> 
     ) 
    } 
} 

// render the application 
ReactDOM.render((
    <Router history={hashHistory}> 
     <Route path="/" component={App}> 
      <Route path="parameter" component={ParameterContainer} /> 
      <Route path="sample" component={SelectFilter} /> 
      <Route path="*" component={NoMatch}/> 
     </Route> 
    </Router> 
), document.getElementById('react')) 

輔元件

import React from 'react'; 

export default class ParameterContainer extends React.Component { 

    constructor(props) { 
     super(props); 
     this.state = { parameters: [] }; 
     this.client = rest.wrap(mime); 
     this.fetchFromApi = this.fetchFromApi.bind(this); 

     console.log('Props:' + props); 
    } 

    render() { 
     .... 
    } 

的this.props不包含我所期待的。我需要將數據傳遞給兒童組件。

回答

0

狀態不會傳播到子組件 - 您必須設置子組件上的道具來傳遞數據。您可以使用React.cloneElement將屬性添加到兒童:

let childrenWithProps = React.cloneElement({this.props.children, { 
     userid: this.state.userId, 
     ... 
    }); 

,最好的辦法是使用終極版來管理Redux的存儲應用程序數據和存儲應用水平狀態。如果你不使用Redux,你也可以考慮使用反應Context。根據文檔,你可以使用右鍵,如果:

要通過組件樹數據,而不必 在各個層面手動向下傳遞道具

0

要通過stateprops到子組件,您可以明確他們的Route節點上

<Route path="parameter" component={ParameterContainer} parentState={this.state} /> 

你可以的話,訪問它們的子組件爲props

constructor(props) { 
    super(props) 
    console.log('parentState:' + props.parentState); 
} 

這裏有更好,更詳細的解答:react-router - pass props to handler component