我需要捕捉这样的网址:
localhost:3000/mypage/name/123/234/345/456
我知道我可以使用这样的路线:
<Route path='/mypage/:pagename/:ids' component={MyComponent}/>
我不知道如何在 ids 中输入一个整数数组(我知道实际上它们是字符串)。请注意名称后项目上的数字可能会更改。
有什么帮助吗?谢谢你们。
您只需要为 id 使用一个路由参数。
所以你的网址必须是这样的:
localhost:3000/mypage/name/123,234,345,456
您可以像这样访问此 ID:
const ids= this.props.match.params.ids; //if functional component, props...
const idsIntArray = ids.split(',').map(Number); // [123, 234, 345, 456]
作为替代方案,将您的 ID 作为查询字符串发送会更合适。
所以你的网址可以是:
localhost:3000/mypage/name?ids=123,234,345,456
在您的组件中,您可以获得 ids 查询字符串,并将其解析为一个数组。
解析查询字符串的最简单方法是使用一个名为query-string
. 安装npm i query-string
并导入后,您可以读取 ids 查询字符串并将其转换为 int 数组,如下所示:
import queryString from 'query-string'
const ids= queryString.parse(this.props.location.search.ids); //if functional component, props...
const idsIntArray = ids.split(',').map(Number); // [123, 234, 345, 456]
有了这个,在你的 Route 定义中,不需要在 url 中放置 ids:
<Route path='/mypage/:pagename' component={MyComponent}/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句