簡體   English   中英

如何將props傳遞給react-router 1.0組件?

[英]How to pass props to react-router 1.0 components?

請注意,盡管問題本身在很大程度上是對此的重復,但它涉及的另一版本支持此問題。 鏈接的問題已接受舊版本的答案

我對預期的工作流程很困惑。

假設我有一個菜單系統,其中單擊每個項目都使用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組件通過更新道具中的國家來對狀態變化做出反應。 除了-因為我不應該在子組件上更新props-會產生不變錯誤之外,我應該在頂層進行更新。 但是,頂層是路由器本身所以現在我只是失去了-在應該聽取的變化和更新的道具?

(由於我認為它需要一些更清晰的文檔,因此被交叉發布到問題跟蹤器中)

閱讀react-router 0.13-> 1.0 Upgrade Guide本示例使我了解以下內容:

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

與其直接包含子組件,不如克隆它們並注入新屬性。 (守護程序處理沒有​​要渲染的子組件的情況。)現在,當子組件渲染時,它可以在this.props.newprop處訪問所需的屬性。

簡單的方法是只使用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) ,只需觸發this.props.onLoadData(data) ,數據便會與當前的props合並。

閱讀Router.createElement文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM