如何将附加参数传递给我要转换到的组件。
我的routes.js如下。我声明了两条路径,一条用于authorList,另一条用于特定作者的详细信息。
var routes = (
<Route path="/" component={require('./components/main')}>
<Route path="authors" component={require('./components/authors/authorPage')}/>
<Route path="authors/:authorId" component={require('./components/authors/AuthorDetails')}/>
</Route>
);
module.exports = routes;
在我的authorList页面中有如下功能。
showAuthorDetails(authorId) {
var myExtraParams = { key1 : val1, key2 : val2};
hashHistory.push(`/authors/${authorId});
}
现在在我的 AuthorDetail 页面中,我可以通过执行以下操作来获取authorId
this.props.params.authorId
但我也想将 myExtraParams 作为对象传递,但不想在 url 中声明和传递它。 我想以某种方式访问新组件中的 myExtraParams,也许可以说是这样做
this.props.params.myExtraParams
应该给 mt 对象。 (就像在 Angular UI 路由器中使用 stateParams 发生的方式一样)
我怎样才能做到这一点?
最佳答案
您可以尝试更改路线的结构,如下所示:
var routes = (
<Route path="/" component={require('./components/main')}>
<Route path="authors" component={require('./components/authors/authorPage')}>
<Route path="author/:authorId" component={require('./components/authors/AuthorDetails')}/>
</Route>
</Route>
);
然后在您的作者列表页面中您可以执行以下操作
...
renderAuth() {
if (this.props.children === null) {
return(
....your default authorList
)
} else {
return React.cloneElement(this.props.children || <div />, {myExtraParams: myExtraParams});
}
}
render() {
<div>
{this.renderAuth()}
</div>
}
showAuthorDetails(authorId) {
hashHistory.push(`/authors/author/${authorId});
}
...
然后您应该能够在您的authorsDetail页面中访问this.props.myExtraParams
关于reactjs - 在 React Router 中传递附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35431276/