简体   繁体   中英

How to pass URL params to render function in ReactJS

I have React Router that looks like this:

<Switch>
  <Route exact path="/" render={() => <DashboardView {...dashboardViewProps} />} />
  <Route path="/blocks" render={() => <BlocksView {...blocksViewProps} />} />
  <Route path="/chaincodes" render={() => <ChaincodeView {...chaincodeViewProps} />} />
  <Route path="/channels" render={() => <ChannelsView {...channelsViewProps} />} />
  <Route path="/network" render={() => <NetworkView  {...networkViewProps} />} />
</Switch>

I want to add new route like this:

<Route path="/transactions/:txId" render={() => <TransactionsView {...transactionsViewProps} />} />

How could I pass the txId to the TransactionView constructor which now looks like this:

constructor(props) {
    super(props);
}

Thank you

txId is available to the Router component though the router props, and when you render a component through render props , you need to pass the router props to the component

<Route path="/transactions/:txId" render={(routerProps) => <TransactionsView {...transactionsViewProps} {...routerProps}/>} />

and then in the component you can get it like

constructor(props) {
    super(props);
    this.txId = props.match.params.txId
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM