【问题标题】:How to pass props to react-router 1.0 components?如何将道具传递给 react-router 1.0 组件?
【发布时间】:2015-09-21 12:17:41
【问题描述】:

请注意,虽然问题本身在很大程度上与this 重复,但它涉及应该支持的不同版本。链接的问题已接受旧版本的答案

我对预期的工作流程很困惑。

假设我有一个菜单系统,点击每个项目使用 react-router 导航到从服务器提取一些数据的区域。

url: yoursite/#/lists/countries
----------------------------
Billing Codes | <<Countries>> | Inventory Types 
---------------------------------------------------------
Countries:
---------------
Afghanistan
Azerbaijan
Belarus

类似的路线

Route #/lists component: Lists
   Route billing-codes component: BillingCodes
   Route countries component: Countries
   Route inventory-types component: InventoryTypes

在导航到某个区域之前,我不想从服务器预加载数据,因此在我的 Countries 组件中,componentWillMount 我触发了一个触发事件(我正在使用回流,但是......无论如何)执行 ajax 请求并使用当前国家/地区列表更新自身的商店。

现在Countries 组件通过更新其道具中的国家/地区来响应状态变化。除了 - 合理 - 因为我不应该更新子组件上的道具,所以会产生一个不变的错误,我应该在顶层更新它。但是最顶层是路由器本身,所以现在我迷路了 - 我应该在哪里监听更改和更新道具?

Cross-posted to the issue tracker 我认为它需要一些更清晰的文档)

【问题讨论】:

  • 欣赏它,但我 am 使用 1.0 仍然不明白。很高兴看到原始问题或此处的答案,尽管原始问题似乎已经接受了一个答案(现已过时)。
  • 我前阵子问过类似的问题stackoverflow.com/questions/31168014/…我对这个问题提出了一些想法,但还没有一个明确的答案
  • 你用的是1.0的react-router?它还没有出来,文档也很少。我建议的副本中有一个解决方法。
  • 它在 beta2 中的 npm 上发布。在 github 上的 docs 目录中有文档。我调整了主题以澄清我正在专门寻找 1.0 中的预期工作流程

标签: reactjs react-router


【解决方案1】:

阅读react-router 0.13 -> 1.0 Upgrade Guidethis example 让我明白了以下几点:

{ this.props.children && 
     React.cloneElement(this.props.children, {newprop: this.state.someobject }) }

我们不直接包含子组件,而是克隆它们并注入新属性。 (守卫处理没有要渲染的子组件的情况。)现在,当子组件渲染时,它可以在this.props.newprop访问所需的属性。

【讨论】:

  • 如果 Route 组件的任一 propType 配置为必需,则此方法会导致页面加载错误。
【解决方案2】:

简单的方法是只使用this.state,但如果你绝对必须使用this.props,那么你应该扩展Router.createElement

首先将createElement 属性添加到您的Router 渲染中。

React.render(
  <Router history={history} children={Routes} createElement={createElement} />,
  document.getElementById('app')
);

将所有组件包装在一个新的Container 组件中。

function createElement(Component, props) {
    return <Container component={Component} routerProps={props} />;
}

您的Container 组件可能看起来像这样。将 onLoadData 函数传递给您的组件。

import React from 'react';
import _ from 'lodash';

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = { props: props.routerProps };
  }

  onLoadData(props) {
    var mergedProps = _.merge(this.state.props, props);
    this.setState({ props: mergedProps });
  }

  render() {
    var Component = this.props.component;
    return <Component {...this.state.props} onLoadData={this.onLoadData.bind(this)} />;
  }
}

然后从您加载的组件中,当您从服务器取回数据时,只需触发this.props.onLoadData(data),数据将与您当前的道具合并。

Read the Router.createElement Documentation

【讨论】:

  • 实际上,您可以使用 lodash 之类的工具将传入的数据与this.props 合并,具体取决于复杂程度。
猜你喜欢
  • 2018-04-25
  • 2018-12-14
  • 2018-07-17
  • 2019-05-08
  • 1970-01-01
  • 2015-03-08
  • 2021-12-21
  • 2016-03-19
  • 2018-08-25
相关资源
最近更新 更多