gpt4 book ai didi

javascript - 使用 React Router 为 151 个不同的配置文件创建一个独特的显示页面

转载 作者:行者123 更新时间:2023-12-03 06:26:47 33 4
gpt4 key购买 nike

这是我第一次使用 React Router,所以我对如何解决这个问题有点困惑。在我的主页上,我有 151 个独特的怪物缩略图。当用户单击其中一个缩略图时,我希望用户被带到怪物的“显示页面”。对于 Monsters 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>
);
}
}

在我的路由文件中创建 Route path='/1' 一直到 151 绝对看起来不正确。用户还可以在地址栏中的 localhost:3000/之后输入一个数字 > 152,那么我该如何防止这种情况发生呢?

任何帮助将不胜感激,谢谢!

最佳答案

使用 react 路由器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
);

关于javascript - 使用 React Router 为 151 个不同的配置文件创建一个独特的显示页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617932/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com