使用react路由器为151个不同的配置文件创建一个唯一的显示页面

Create a unique show page for 151 different profiles using react router

本文关键字:一个 唯一 显示 文件创建 路由器 react 151个 配置 使用      更新时间:2023-09-26

这是我第一次使用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
);
相关文章: