将动态状态传递给路由器中的所有路由

React pass dynamic state to all routes in router

我正在尝试将动态状态传递给 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 中的更新状态将其传递给路由,或者这是不可能的并且我这样做是错误的方式?

感谢您的帮助

由于您已经有一个用于保存状态的主要组件,因此您应该将其插入到顶级 Route 组件中,如下所示:

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

然后在你的 RouterHub 组件中,通过 props 传递那些克隆每个子组件,像这样:

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

遇到这种问题会让你想到使用一些状态管理库,比如Redux/Flux。