react hooks 跳转路由传参,但是参数里面会有数组,要怎么传递
时间: 2023-07-21 14:09:31 浏览: 47
在 React 中,我们可以使用 React Router 来进行路由跳转和传递参数。在传递参数时,如果参数中包含数组,我们可以使用 query string 的方式来传递。
例如,假设我们有一个包含数组的参数需要传递,我们可以将其转换为 JSON 字符串,并使用 encodeURIComponent 方法对其进行编码。然后,我们可以将编码后的字符串作为 query string 的值传递给目标路由。
以下是一个示例代码:
```
import React from 'react';
import { Link } from 'react-router-dom';
function MyComponent() {
const myArray = [1, 2, 3];
const encodedArray = encodeURIComponent(JSON.stringify(myArray));
return (
<Link to={`/my-route?myArray=${encodedArray}`}>Go to My Route</Link>
);
}
export default MyComponent;
```
在这个例子中,我们将 myArray 数组转换为 JSON 字符串,并使用 encodeURIComponent 方法对其进行编码。然后,我们将编码后的字符串作为 myArray 参数的值,传递给目标路由的 query string 中。
在目标路由中,我们可以使用 React Router 提供的 useLocation hook 和 query-string 库来获取参数值,并将 JSON 字符串转换为数组。
以下是一个示例代码:
```
import React from 'react';
import { useLocation } from 'react-router-dom';
import queryString from 'query-string';
function MyRoute() {
const { search } = useLocation();
const { myArray } = queryString.parse(search);
const decodedArray = JSON.parse(decodeURIComponent(myArray));
return (
<div>
<p>My Array: {decodedArray.join(', ')}</p>
</div>
);
}
export default MyRoute;
```
在这个例子中,我们使用 useLocation hook 获取当前路由的 query string,然后使用 query-string 库解析参数值。最后,我们将编码后的字符串解码,并将 JSON 字符串转换为数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)