在React中,当你需要在URL的查询参数中传递数组时,由于URL查询参数通常使用key=value
的形式,直接传递数组会导致格式不正确。因此,你需要将数组转换为适合URL的格式。以下是几种常见的方法:
你可以将数组转换为JSON字符串,然后作为查询参数传递。在接收端,再将JSON字符串解析回数组。
import { useNavigate } from 'react-router-dom';
function App() {
const navigate = useNavigate();
const handleClick = () => {
const array = [1, 2, 3];
const queryString = `array=${encodeURIComponent(JSON.stringify(array))}`;
navigate(`/target-page?${queryString}`);
};
return (
<div>
<button onClick={handleClick}>Go to Target Page</button>
</div>
);
}
import { useLocation } from 'react-router-dom';
function TargetPage() {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const arrayString = queryParams.get('array');
const array = JSON.parse(decodeURIComponent(arrayString));
return (
<div>
<h1>Target Page</h1>
<p>Array: {array.join(', ')}</p>
</div>
);
}
另一种方法是使用逗号分隔的字符串来表示数组。
import { useNavigate } from 'react-router-dom';
function App() {
const navigate = useNavigate();
const handleClick = () => {
const array = [1, 2, 3];
const queryString = `array=${array.join(',')}`;
navigate(`/target-page?${queryString}`);
};
return (
<div>
<button onClick={handleClick}>Go to Target Page</button>
</div>
);
}
import { useLocation } from 'react-router-dom';
function TargetPage() {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const arrayString = queryParams.get('array');
const array = arrayString.split(',').map(Number);
return (
<div>
<h1>Target Page</h1>
<p>Array: {array.join(', ')}</p>
</div>
);
}
你也可以将数组的每个元素作为单独的查询参数传递。
import { useNavigate } from 'react-router-dom';
function App() {
const navigate = useNavigate();
const handleClick = () => {
const array = [1, 2, 3];
const queryString = array.map((item, index) => `array[${index}]=${item}`).join('&');
navigate(`/target-page?${queryString}`);
};
return (
<div>
<button onClick={handleClick}>Go to Target Page</button>
</div>
);
}
import { useLocation } from 'react-router-dom';
function TargetPage() {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const array = [];
for (let i = 0; ; i++) {
const value = queryParams.get(`array[${i}]`);
if (value === null) break;
array.push(Number(value));
}
return (
<div>
<h1>Target Page</h1>
<p>Array: {array.join(', ')}</p>
</div>
);
}
以上三种方法都可以在React中有效地传递数组作为URL查询参数。选择哪种方法取决于你的具体需求和应用场景。以下是一些参考链接:
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云