react searchParams的使用
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;
对于
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[]