使用react路由器为151个不同的配置文件创建一个唯一的显示页面
Create a unique show page for 151 different profiles using react router
这是我第一次使用react路由器,所以我有点困惑该怎么做。在我的主页上,我有151个独特的怪物缩略图。当用户点击其中一个缩略图时,我希望用户被带到怪物的"显示页面"。对于怪物href,我正在使用它的索引创建一个唯一的url:
{this.props.pokeList.map((pokemon, index) => {
return (
<div key={index} className="col-xs-6 col-md-2">
<a style={aTagStyle} href={index + 1} className="thumbnail">
<img src={`https://s3-eu-west-1.amazonaws.com/calpaterson-pokemon/${index + 1}.jpeg`} style={imgStyle} />
<p style={textStyle}>{pokemon.entry_number}</p>
<p style={textStyle}>{pokemon.pokemon_species.name}</p>
</a>
</div>
);
})}
这是我当前的路线文件:
class PokedexRouter extends Component {
render() {
return (
<Router history={ hashHistory } >
<Route path='/' component={App} >
</Route>
</Router>
);
}
}
在我的路由文件中创建路由路径='/1'一直到151似乎绝对不对。用户也可以在地址栏中的localhost:3000/之后输入一个>152的数字,那么我该如何防止这种情况发生呢?。
如有任何帮助,我们将不胜感激,谢谢!
使用react router router参数。如果用户试图输入不受支持的值,则可以使用onEnter进行重定向。
const validatedImageId = (nextState, replace, callback) => {
const imageId = parseInt(nextState.params.imageId, 10);
if(isNaN(imageId) || imageId < 0 || imageId > 151) {
replace('/'); // redirect to main page
}
callback();
};
class PokedexRouter extends Component {
render() {
return (
<Router history={ hashHistory } >
<Route path='/' component={App} >
<Route path='image/:imageId' component={ImagePage} onEnter={ validatedImageId } /> // the imageId will be a parameter, that the ImagePage component will receive
</Route>
</Router>
);
}
}
{this.props.pokeList.map((pokemon, index) => {
return (
<div key={index} className="col-xs-6 col-md-2">
<Link style={aTagStyle} to={ `image/${index + 1}` } className="thumbnail"> // use react-router Link component to link to the route
<img src={`https://s3-eu-west-1.amazonaws.com/calpaterson-pokemon/${index + 1}.jpeg`} style={imgStyle} />
<p style={textStyle}>{pokemon.entry_number}</p>
<p style={textStyle}>{pokemon.pokemon_species.name}</p>
</a>
</div>
);
})}
const ImagePage = ({ params }) => ( // extract the params from the props
<img src=`https://s3-eu-west-1.amazonaws.com/calpaterson-pokemon/${ params.imageId }.jpeg`} /> // use params.imageId to get the original index of the image
);
相关文章:
- 多个ID和一个唯一的名称
- 如何生成一个唯一的链接,该链接将加载一个会话,其中包含客户端可用的某些文档
- 警告:数组或迭代器中的每个子节点都应该有一个唯一的“键”道具
- 为变量指定一个唯一的名称 JavaScript/jQuery
- 未捕获的异常:每个数据元素都必须实现一个唯一的“id”属性slick.dataview.js
- 如何将用户名附加到我的 ./profile/
URL 中,以便每个用户都有一个唯一的页面.-意思 - - 每次 while 循环运行时调用 javascript,以从数据库中给出一个唯一的时间
- 将一个元素与一个唯一的数字相关联
- 如何分配或附加一个唯一的ID在javascript与行整数从html
- 给动态生成的文本框一个唯一的名字
- 是否有一种更简单的方法来使用lodash从多个对象集合中构造一个唯一值的数组?
- sequelize + sequelize-hierarchy:如何在每个级别强制一个唯一的组织名称
- 创建一个唯一的JavaScript对象
- 如何使用node js与mongoose创建一个唯一的json元素列表
- 如何在每次调用指令时创建一个唯一的作用域(AngularJS)
- 是否可以将一个唯一的CSS类附加到多个<李>元素,或者使用Jquery对它们重新排序
- D3.js:在一个有序的尺度中获取每一个唯一的值
- 每次while循环运行时调用javascript,给出一个唯一的波形
- 如何生成一个唯一的id,每次我按下一个按钮在JavaScript
- 多个主机名对每个URL都需要一个唯一的iframe