我正在尝试将动态状态传递给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中更新状态将其传递给路由,或者这是不可能的,我这样做的方式是错误的吗?
感谢您的帮助
答案 0 :(得分:1)
由于您已拥有用于保存状态的主要组件,因此应将其插入顶级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这样的状态管理库。