React 路由器:从 objects 创建 'Link to' 路径

React router: Create 'Link to' paths from objects

我有一个从 Dropbox api 中提取的图像和标题的索引。这些(单击时)已经创建并安装了新组件。我正在尝试将 react-router 集成到该项目中,但正在努力使用我已经创建的数组生成 Link 到= 路径。

import { BrowserRouter, Route, Link } from 'react-router-dom'

//titles variable created via api
var titles=["title one","title two","title three",...]


class Index extends React.Component{

    render(){
        if(!this.props.imageSource.length)
            return null;
            let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>)
            let images = this.props.imageSource.map((el, i) =>

                <div className="imageContainer">
                  <img key={i} className='indexImages' src={el} onClick = {this.props.indexTitleClick.bind(this,titles[i])}/>
                  <Link to={titles[i]} className="imageTitle" onClick = {this.props.indexTitleClick.bind(this,titles[i])}>{titles[i]}</Link>
                </div>
            )



        return (
            <div className="indexWrapper">
                {images}
            </div>

        );
    }
}

如您所见,我正在尝试使用与生成 imageTitles 相同的方法,但在呈现时 href 只是“/”。是否可以通过这种方式动态生成路径?

p.s。我尽量使代码简洁明了,但很乐意在需要时添加更多信息。

不确定您是否意识到这一点,但您忽略了 titles

var titles=["title one","title two","title three",...] // from outside your component
let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>) // inside render

然后,您正在尝试 link 到 titles 数组的成员,但它包含以下格式的成员:

<p>{el}</p>

首先你必须创建一个根目录class,你将在其中声明一些路径,如下例

 <Router history={browserHistory} >               
    <Root path="/:pathVariable" component={ComponentClass}/>           
 </Router>

然后使用 browserHistory.push("/path") 您将导航到 http://host:port/path