2016-12-17 140 views
0

我試圖將動態狀態傳遞給React路由器中的所有路由,特別是購物車(對象數組)。React將動態狀態傳遞給路由器中的所有路由

佈局是我有一個父組件,其中包含路由器和所有的路線,並在那我想存儲購物車的狀態,並將其傳遞給路由(所以基本上所有的路線將有權訪問它)。我一直在嘗試幾件不同的事情,並通過在論壇上查找一段時間來排除故障,但我無法得到它。這是最新的設置,我有:

- Main.jsx

// This is the app entry point 
import React, { Component } from 'react'; 
import { render } from 'react-dom'; 
import RouterHub from './RouterHub.jsx'; 

render((
    <RouterHub /> 
), document.getElementById('root')); 

- RouterHub.jsx

import React, { Component } from 'react'; 
import { render } from 'react-dom'; 
import { Router, Route, hashHistory } from 'react-router' 
import Home from './Home.jsx'; 
import Dogs from './Pages/Other.jsx'; 

class RouterHub extends Component { 

    constructor(props) { 
     super(props); 
     this.addItem = this.addItem.bind(this); 
     this.state = { 
      cart: [] 
     }; 
    } 

    addItem(item) { 
     let newCart = this.state.cart.splice(); 
     newCart.push(item); 
     this.setState({cart: newCart}); 
    } 

    render() { 
     return(
      <Router history={hashHistory}> 
       <Route path="/" component={Home} cart={this.state.cart} addItem={this.addItem} /> 
       <Route path="/other" component={Other} cart={this.state.cart} addItem={this.addItem}/> 
      </Router> 
     ); 
    } 
} 

export default RouterHub; 

- Home.jsx

import React, { Component } from 'react'; 
import Slideshow from './Home/Slideshow.jsx'; 
import Navbar from './Constants/Navbar.jsx'; 
import Footer from './Constants/Footer.jsx'; 

class Home extends Component { 
    constructor(props) { 
     super(props); 
    } 

    render() { 
     return(
      <div> 
       <button onClick={() => this.props.route.addItem('potato')}>click me</button> 
       <Navbar /> 
       // All the JSX content, I've removed to make it succint 
       <Footer /> 
      </div> 
     ); 
    } 
} 

export default Home; 

基本上我想要的是在Home.jsx中,當我單擊該按鈕時,我想要另一個馬鈴薯添加到購物車。然而,與此設置我得到的錯誤:

bundle.js:46451 Warning: [react-router] You cannot change <Router routes>; it will be ignored 

我如何得到它,以便在RouterHub更新狀態過渡,爲的路由,或者是不可能的,我做這一切的錯誤方式?

感謝所有幫助

回答

1

既然你已經有牽着你的狀態的主要成分,你應該插入在頂部層級路由組件是這樣的:

render((
    <Router history={browserHistory}> 
    <Route path="/" component={RouterHub}> 
     <Route path="home" component={Home}/> 
    </Route> 
    </Router> 
), document.getElementById('root')) 

然後在你的RouterHub組件,通過那些克隆每個兒童組件與道具,像這樣:

{ 
    React.Children.map(this.props.children, (child) => { 
     return React.cloneElement(child, this.props) 
    }) 
} 

碰到這種問題會讓你想到我們像Redux/Flux這樣的國家管理庫。

+0

感謝您的回覆。當我嘗試時,在RouterHub中它說'this.props.children'爲空,即使其他路由是它的子節點。 – Jayce444

+0

nvm讓我的組件設置錯誤。現在都在工作。謝謝!! :d – Jayce444