2016-10-11 75 views
1

我想弄清楚使用React状态管理与react-router的最简单方法。路由器在像Redux这样的状态容器上工作得很好,但是如果你想用React来管理你的状态呢?如果要将状态存储在单个根组件中,并将其作为道具显式传递给子组件,会怎么样?而且,您希望代码看起来漂亮并且高效?只需使用与路由器的React状态管理

最简单的解决办法是使用路由器作为一个孩子的孩子组成部分,但我知道它不喜欢这样的工作:

import { Component } from 'react' 
import { Router, Route, hashHistory } from 'react-router' 
import { Catalog, Cart, Checkout } from './shopping' 
import { Menu, Errors } from './navigation' 
import { render } from 'react-dom' 

class App extends Component { 

    constructor(props) { 
    super(props) 
    this.state = { 
     inventoy: [ ... ], 
     cart: [ ... ]   
    } 
    } 

    render() { 
    return (
     <div className="app"> 
     <Menu /> 
     <Router history={hashHistory}> 
      <Route path="/" component={Catalog} inventory={inventory} /> 
      <Route path="/cart" component={Cart} cart={cart} /> 
     </Router> 
     <Errors /> 
     </div> 
    ) 
    } 
} 

render(<App />, document.getElementById('target')) 

如此看来,路由器想成为父母,和该方法将是嵌套的路线。但要做到这一点,你必须复制的元素,并明确通过所有的状态变量的所有的孩子们的:

import { Component } from 'react' 
import { Router, Route, hashHistory } from 'react-router' 
import { Catalog, Cart, Checkout } from './shopping' 
import { Menu, Errors } from './navigation' 
import { render } from 'react-dom' 

class App extends Component { 

    constructor(props) { 
     super(props) 
     this.state = { 
      inventoy: [ ... ], 
      cart: [ ... ] 
     } 
    } 

    render() { 

     const { children } = this.props 
     const { inventory, cart } = this.state 

     return (
      <div className="app"> 
       <Menu /> 
       {React.cloneElement(children, {inventory, cart})} 
       <Errors /> 
      </div> 
     ) 
    } 
} 

render(
    <Router history={hashHistory}> 
     <Route path="/" component={App}> 
      <Route path="/" component={Catalog} /> 
      <Route path="/cart" component={Cart} /> 
     </Route> 
    </Router>, 
    document.getElementById('target') 
) 

问题这这种做法是额外的数据被传递到嵌套组件。购物车组件不需要库存,但无论如何它都会得到它。目录组件不需要购物车数据,但无论如何它都会得到它。显然,这可能会失去控制与很多状态和许多状态数据。克隆组件似乎效率不高。

有没有我缺少的东西,有没有一种更简单的方法来将状态从根组件传递到使用路由器的子组件,还是在使用路由器时,您总是必须使用状态容器,如REDX?

反应状态是一种很好,反应路由器是一种很好。有没有更好的方法一起使用它们?路由器简单到足以让初学者轻松整合吗?

回答

0

我发现了一个非常简单的路由替代解决方案。即为不同路由重复使用相同的组件,并在组件内通过检查location.pathname或params来显示approprate元素。

render(
     <Router history={hashHistory}> 
     <Route path="/" component={App} /> 
     <Route path="/cart" component={App} /> 
     <Route path="/catalog/:category" component={App} /> 
     </Router>, 
     document.getElementById('target') 
    ) 

一切呈现应用程序组件,但您可以使用应用程序的渲染方法中的路由器道具。

render() { 

    var currentLocation = this.props.location.pathname 
    var category = this.props.params.category 

}