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