在React Router中传递其他参数

Ani*_*ket 6 reactjs react-router

如何将其他参数传递给我要转换到的组件.

我有我的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;
Run Code Online (Sandbox Code Playgroud)

在我的authorList页面中,有如下功能.

showAuthorDetails(authorId) {            

    var myExtraParams = { key1 : val1, key2 : val2};
    hashHistory.push(`/authors/${authorId});     
}
Run Code Online (Sandbox Code Playgroud)

现在在我的AuthorDetail页面中,我可以通过执行来获得authorId

this.props.params.authorId
Run Code Online (Sandbox Code Playgroud)

但我也希望将myExtraParams作为对象传递,但不想在url中声明并传递它.我想以某种方式访问​​新组件中的myExtraParams,也许就像这样做

this.props.params.myExtraParams
Run Code Online (Sandbox Code Playgroud)

应该给mt这个对象.(就像使用stateParams在Angular UI路由器中发生的那样)

我怎样才能做到这一点?

deo*_*owk 2

您可以尝试更改路线的结构,如下所示:

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>
);
Run Code Online (Sandbox Code Playgroud)

然后在你的authorList页面你可以做

...
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});     
}
...
Run Code Online (Sandbox Code Playgroud)

然后,您应该能够在authorsDetail页面中访问this.props.myExtraParams