只需在Router中使用React State Management



我正试图找出使用React状态管理与React -router的最简单方法。Router与Redux这样的状态容器配合得很好,但是如果你想用React来管理你的状态呢?如果你想将状态存储在一个根组件中,并将其作为props显式地传递给子组件,该怎么办?而且,您希望代码看起来美观高效?

最简单的解决方案是将Router作为子组件使用,但我知道它不是这样工作的:
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')
)

这种方法的问题是额外的数据被传递给嵌套的组件。Cart组件不需要库存,但无论如何它都会得到库存。Catalog组件不需要购物车数据,但无论如何它都会获取这些数据。很明显,如果有很多状态和很多状态数据,这可能会失控。而且克隆组件似乎效率不高。

是否有我缺少的东西,是否有更简单的方法将状态从根组件传递到使用路由器的子组件,或者当使用路由器时,您是否总是必须使用像redux这样的状态容器?

React状态很好,React -router也很好。有没有更好的方法把它们一起使用呢?路由器是否足够简单,初学者可以轻松使用?

我为非常简单的路由找到了另一种解决方案。这是为了在不同的路由中重用相同的组件,并在组件中通过检查位置来显示适当的元素。路径名或参数

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

一切都会渲染应用组件,但你可以在应用的render方法中使用router道具。

render() {
    var currentLocation = this.props.location.pathname
    var category = this.props.params.category
}

最新更新