小编典典

将道具传递到React Router子路线

reactjs

我无法克服React Router的问题。场景是我需要让子级路由从状态父级组件和路由传递一组道具。
我想做的就是通过childRouteApropsA,然后通过childRouteBpropsB。但是,我能弄清楚如何做到这一点的唯一方法是同时通过RouteHandler两者propsApropsB这意味着每条子路线都会获得每条子道具,而不论其是否相关。目前,这并不是一个阻塞问题,但是我可以看到有一段时间我将使用两个相同的组件,这意味着propA上的键将被propB的键覆盖。

# routes
routes = (
  <Route name='filter' handler={ Parent } >
    <Route name='price' handler={ Child1 } />
    <Route name='time' handler={ Child2 } />
  </Route>
)

# Parent component
render: ->
  <div>
    <RouteHandler {...@allProps()} />
  </div>

timeProps: ->
  foo: 'bar'

priceProps: ->
  baz: 'qux'

# assign = require 'object-assign'
allProps: ->
  assign {}, timeProps(), priceProps()

这实际上以我期望的方式工作。当我链接到/filters/time我得到的Child2组件呈现。当我去的时候/filters/price我得到的Child1组件呈现。问题是,做这个过程,Child1并且Child2都通过了allProps(),即使他们只需要价格和时间的道具,分别。如果这两个组件具有相同的道具名称,这通常会成为一个问题,通常来说,用不必要的道具膨胀组件(因为在我的实际案例中有两个以上的孩子)并不是一个好习惯。
因此,总而言之
,有没有一种方法可以RouteHandler在我转到时间路线(filters/time)时传递timeProps,并且仅RouteHandler在我转到价格路线(filters/price)时将priceProps
传递至,并避免将所有道具传递给所有子路线?


阅读 306

收藏
2020-07-22

共1个答案

小编典典

我遇到了类似的问题,发现您可以访问路线组件中的Route穿过设置的道具this.props.route。知道了这一点,我就这样组织了我的组件:

index.js

React.render((
  <Router history={new HashHistory()}>
    <Route component={App}>
        <Route
          path="/hello"
          name="hello"
          component={views.HelloView}
          fruits={['orange', 'banana', 'grape']}
        />
    </Route>
  </Router>
), document.getElementById('app'));

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <div>{this.props.children}</div>;
  }
}

HelloView.js

class HelloView extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <div>
      <ul>
        {this.props.route.fruits.map(fruit => 
          <li key={fruit}>{fruit}</li>
        )}
      </ul>
    </div>;
  }
}

这是使用react-router v1.0-beta3。希望这可以帮助!


好的,现在我对您的问题有了更好的了解,这是您可以尝试的方法。

由于您的孩子道具来自单亲,因此您的父组件(而不是react-router)应该是管理渲染哪个孩子的组件,以便您可以控制传递哪些道具。

您可以尝试更改路线以使用参数,然后在父组件中检查该参数以呈现适当的子组件。

路线

<Route name="filter" path="filter/:name" handler={Parent} />

父组件

render: function () {
  if (this.props.params.name === 'price') {
    return <Child1 {...this.getPriceProps()} />
  } else if (this.props.params.name === 'time') {
    return <Child2 {...this.getTimeProps()} />
  } else {
    // something else
  }
}
2020-07-22