searchParams 用于解析和操作URL的查询参数。可以使用searchParams来获取、添加、删除和修改URL中的查询参数。

例如:

import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
// 获取当前URL的查询参数
const searchParams = new URLSearchParams(window.location.search);
// 获取特定查询参数的值
const paramValue = searchParams.get('paramName');
console.log(paramValue);
// 添加查询参数
searchParams.append('newParam', 'value');
// 修改查询参数的值
searchParams.set('paramName', 'updatedValue');
// 删除查询参数
searchParams.delete('paramName');
// 更新URL的查询参数
const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
window.history.replaceState(null, '', newUrl);
}, []);
return <div>My Component</div>;
};
export default MyComponent;

对于
http://localhost:3000/show_result_as_map/1446?calculation_result_id=1175&material_id=18

import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
// 获取当前URL的查询参数
const searchParams = new URLSearchParams(window.location.search);
// 获取特定查询参数的值
const calculationResultId = searchParams.get('calculation_result_id');
const materialId = searchParams.get('material_id');
console.log(calculationResultId); // 输出:1175
console.log(materialId); // 输出:18
// 添加查询参数
searchParams.append('newParam', 'value');
// 修改查询参数的值
searchParams.set('calculation_result_id', 'updatedValue');
// 删除查询参数
searchParams.delete('material_id');
// 更新URL的查询参数
const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
window.history.replaceState(null, '', newUrl);
}, []);
return <div>My Component</div>;
};
export default MyComponent;

上面的代码中使用了React的

useEffect
钩子,并将其依赖数组设置为空数组
[]
,以确保只在组件加载时执行一次。这样可以在组件加载时对URL的查询参数进行处理。